C#将图片和字节流互相转换并显示到页面上

C#将图片和字节流互相转换并显示到页面上,第1张

概述图片转换字节流先要转换的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,imgByte.Length);files.Close();returnimgByte;}}}

将字节流转换为图片文件显示到页面

//Byte[] result;System.IO.MemoryStream ms =new MemoryStream(result,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,buffersize); //返回图片字段buffer if (count!=0) context.Response.OutputStream.Write(buffer,count); } } public bool IsReusable { get { return false; } }}

以上就是本文的全部内容,希望对大家学习C#将图片和字节流互相转换并显示到页面上有所帮助。

总结

以上是内存溢出为你收集整理的C#将图片和字节流互相转换并显示到页面上全部内容,希望文章能够帮你解决C#将图片和字节流互相转换并显示到页面上所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1260866.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-08
下一篇2022-06-08

发表评论

登录后才能评论

评论列表(0条)

    保存