C#将图片和字节流互相转换并显示到页面上
投稿:mrr
本文主要介绍用C#实现图片转换成字节流,字节流转换成图片,并根据图片路径返回图片的字节流,有需要的朋友可以参考下
图片转换成字节流先要转换的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#将图片和字节流互相转换并显示到页面上有所帮助。