c# image转换为bitmap_C# Byte[]、Image、Bitmap 之间的相互转换

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 15:54   1617   0

///

///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;

}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP