C#将图片和字节流互相转换并显示到页面上
程序员文章站
2023-11-16 22:50:28
图片转换成字节流先要转换的image对象,转换之后返回字节流。字节流转换成图片,要转换的字节流,转换得到的image对象,根据图片路径返回图片的字节流,感兴趣的朋友看下下面...
图片转换成字节流先要转换的image对象,转换之后返回字节流。字节流转换成图片,要转换的字节流,转换得到的image对象,根据图片路径返回图片的字节流,感兴趣的朋友看下下面的代码。
c#将图片和字节流相互转换代码:
usingsystem; usingsystem.collections.generic; usingsystem.linq; usingsystem.text; usingsystem.drawing; usingsystem.io; namespacemicrosoft.form.base { classimagetobyte { /// <summary> /// 图片转换成字节流 /// </summary> /// <param name="img">要转换的image对象</param> /// <returns>转换后返回的字节流</returns> publicstaticbyte[] imgtobyt(image img) { memorystream ms = newmemorystream(); byte[] imagedata = null; img.save(ms, system.drawing.imaging.imageformat.jpeg); imagedata = ms.getbuffer(); returnimagedata; } /// <summary> /// 字节流转换成图片 /// </summary> /// <param name="byt">要转换的字节流</param> /// <returns>转换得到的image对象</returns> publicstaticimage byttoimg(byte[] byt) { memorystream ms = newmemorystream(byt); image img = image.fromstream(ms); returnimg; } // /// <summary> /// 根据图片路径返回图片的字节流byte[] /// </summary> /// <param name="imagepath">图片路径</param> /// <returns>返回的字节流</returns> privatestaticbyte[] getimagebyte(stringimagepath) { filestream files = newfilestream(imagepath, filemode.open); byte[] imgbyte = newbyte[files.length]; files.read(imgbyte, 0, imgbyte.length); files.close(); returnimgbyte; } } }
将字节流转换为图片文件显示到页面上
//byte[] result; system.io.memorystream ms =new memorystream(result, 0, result.length) response.clearcontent(); response.contenttype = "image/gif"; response.binarywrite(ms.toarray()); 或者添加一个处理图片的handler,内容如下: <%@ webhandler language="c#" class="handler" %> using system.web; using system.io; public class handler : ihttphandler { public void processrequest (httpcontext context) { int categoryid = int.parse(context.request.querystring["categoryid"]); //调用categories.getpicture取得图片stream stream stream = categoriespicture.getpicture(categoryid); if (stream !=null) { //取得图片stream大小 int buffersize = (int)stream.length; //建立buffer system.byte[] buffer = new system.byte[buffersize ] ; //调用stream.read,从stream读取到buffer,并返回count int count = stream.read(buffer, 0, buffersize); //返回图片字段buffer if (count!=0) context.response.outputstream.write(buffer, 0, count); } } public bool isreusable { get { return false; } } }
以上就是本文的全部内容,希望对大家学习c#将图片和字节流互相转换并显示到页面上有所帮助。
推荐阅读