栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

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

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

图片转换成字节流先要转换的IMage对象,转换之后返回字节流。字节流转换成图片,要转换的字节流,转换得到的Image对象,根据图片路径返回图片的字节流,感兴趣的朋友看下下面的代码。

C#将图片和字节流相互转换代码:

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Drawing;
usingSystem.IO;
namespaceMicrosoft.Form.base
{
classImageToByte
{
/// 
/// 图片转换成字节流
/// 
/// 要转换的Image对象
/// 转换后返回的字节流
publicstaticbyte[] ImgToByt(Image img)
{
MemoryStream ms = newMemoryStream();
byte[] imagedata = null;
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
imagedata = ms.GetBuffer();
returnimagedata;
}
/// 
/// 字节流转换成图片
/// 
/// 要转换的字节流
/// 转换得到的Image对象
publicstaticImage BytToImg(byte[] byt)
{
MemoryStream ms = newMemoryStream(byt);
Image img = Image.FromStream(ms);
returnimg;
}
//
/// 
/// 根据图片路径返回图片的字节流byte[]
/// 
/// 图片路径
/// 返回的字节流
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#将图片和字节流互相转换并显示到页面上有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/124852.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号