c#实现图片与字节流相互转换的代码

发布时间:2020-12-30编辑:脚本学堂
用c#.net实现字节流转换为图片,图片转换为字节流,以及根据图片的路径返回字节流,有需要的朋友,可以参考下。
复制代码 代码示例:
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;
}
}
}