C# 图片与byte[]之间以及byte[]与string之间的转换
using System; using System.IO; using System.Drawing; using System.Windows.Forms; using System.Drawing.Imaging; public class ImageConvert { //主要通过Stream作为中间桥梁 public static Image ByteArrayToImage(byte[] iamgebytes) { MemoryStream ms = new MemoryStream(iamgebytes); Image image = Image.FromStream(ms); return image; } public static byte[] ImageToByteArray(Image image) { MemoryStream ms = new MemoryStream(); image.Save(ms, image.RawFormat); return ms.ToArray(); } public static string ByteArrayToString(byte[] bytes) { return Convert.ToBase64String(bytes); } public static string StringToByteArray(string image) { return Convert.FromBase64String(image); } }
如何将jpg格式图像文件转化成一系列二进制数据,又如何将此二进制数据转化成jpg格式的文件? 常常因为某种特殊的需要,如网络传输或者保存到数据库,或分块存放或者压缩等,总要将图片转换成字节数组。
Image image = Image.FromFile("C:\\1.jpg"); MemoryStream ms = new MemoryStream(); image.Save(ms,ImageFormat.Jpeg); ms.Flush(); ms.Seek(0,SeekOrigin.Begin); byte [] buffer = new byte[ms.Length]; ms.Read(buffer,0,(int)ms.Length);//这里已经转成了字节 MemoryStream ms2 = new MemoryStream(buffer,0,buffer.Length); ms2.Seek(0,SeekOrigin.Begin); Image image2 = Image.FromStream(ms2); image2.Save("C:\\2.jpg",ImageFormat.Jpeg); System.Drawing.Image image = System.Drawing.Image.FromFile("D:\\1.jpg"); System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); ms.Flush(); ms.Seek(0, System.IO.SeekOrigin.Begin); byte[] buffer = new byte[ms.Length]; ms.Read(buffer, 0, (int)ms.Length);//这里已经转成了字节 System.IO.MemoryStream ms2 = new System.IO.MemoryStream(buffer, 0, buffer.Length); ms2.Seek(0, System.IO.SeekOrigin.Begin); System.Drawing.Image image2 = System.Drawing.Image.FromStream(ms2); image2.Save("D:\\2.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); image.Dispose(); image2.Dispose(); ms.Dispose(); ms2.Dispose(); buffer = null; winform直接显示二进制数据中的图片 //读取DataSet中以二进制(Image)形式保存的图片 byte[] byteImage = (byte[])dataSet11.tBGPicture.Rows[2]["PicContent"]; //转成MemoryStream类型 System.IO.MemoryStream stream = new System.IO.MemoryStream(byteImage, true); //stream.Write(byteImage, 0, byteImage.Length); //显示图片 pictureBox1.Image = Image.FromStream(stream); //关闭stream stream.Close();