当前位置: 编程技术>.net/c#/asp.net
c#实现图片与字节流相互转换的代码
来源: 互联网 发布时间:2014-08-30
本文导语: 代码示例: usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Drawing; usingSystem.IO; namespaceMicrosoft.Form.Base { classImageToByte { /// /// 图片转换成字节流 /// /// 要转换的Image对象 /// 转换后返回的字节流 p...
代码示例:
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;
}
}
}
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;
}
}
}