C# 将字节流转换为图片的实例方法
程序员文章站
2023-12-03 08:37:22
复制代码 代码如下:usingsystem; usingsystem.collections.generic; usingsystem.linq; usingsystem....
复制代码 代码如下:
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;
}
}
}