///
///Convert Image to Byte[]///
///
///
public static byte[] ImageToBytes(Image image)
{
ImageFormat format=image.RawFormat;using (MemoryStream ms = newMemoryStream())
{if(format.Equals(ImageFormat.Jpeg))
{
image.Save(ms, ImageFormat.Jpeg);
}else if(format.Equals(ImageFormat.Png))
{
image.Save(ms, ImageFormat.Png);
}else if(format.Equals(ImageFormat.Bmp))
{
image.Save(ms, ImageFormat.Bmp);
}else if(format.Equals(ImageFormat.Gif))
{
image.Save(ms, ImageFormat.Gif);
}else if(format.Equals(ImageFormat.Icon))
{
image.Save(ms, ImageFormat.Icon);
}byte[] buffer = new byte[ms.Length];//Image.Save()会改变MemoryStream的Position,需要重新Seek到Begin
ms.Seek(0, SeekOrigin.Begin);
ms.Read(buffer,0, buffer.Length);returnbuffer;
}
}///
///Convert Byte[] to Image///
///
///
public static Image BytesToImage(byte[] buffer)
{
MemoryStream ms= newMemoryStream(buffer);
Image image=System.Drawing.Image.FromStream(ms);returnimage;
}///
///Convert Byte[] to a picture and Store it in file///
///
///
///
public static string CreateImageFromBytes(string fileName, byte[] buffer)
{string file =fileName;
Image image=BytesToImage(buffer);
ImageFormat format=image.RawFormat;if(format.Equals(ImageFormat.Jpeg))
{
file+= ".jpeg";
}else if(format.Equals(ImageFormat.Png))
{
file+= ".png";
}else if(format.Equals(ImageFormat.Bmp))
{
file+= ".bmp";
}else if(format.Equals(ImageFormat.Gif))
{
file+= ".gif";
}else if(format.Equals(ImageFormat.Icon))
{
file+= ".icon";
}
System.IO.FileInfo info= newSystem.IO.FileInfo(file);
System.IO.Directory.CreateDirectory(info.Directory.FullName);
File.WriteAllBytes(file, buffer);returnfile;
}