圖片轉換成字節流先要轉換的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#將圖片和字節流互相轉換并顯示到頁面上有所幫助。
新聞熱點
疑難解答