C# · 12月 21, 2021

C# 将字节流转换为图片的实例方法

@H_403_1@复制代码 代码如下:
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;
}
}
}