如何转换字节数组中的图像

任何人都可以build议如何可以将图像转换为字节数组,反之亦然。 如果有人有一些代码样本帮助我。 我正在开发一个WPF应用程序,并启用findstream阅读器。

示例代码将图像更改为字节数组

public byte[] ImageToByteArray(System.Drawing.Image imageIn) { using (var ms = new MemoryStream()) { imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif); return ms.ToArray(); } } 

C#图像到字节数组和字节数组到图像转换器类

对于将图像对象转换为byte[]您可以执行如下操作:

 public static byte[] converterDemo(Image x) { ImageConverter _imageConverter = new ImageConverter(); byte[] xByte = (byte[])_imageConverter.ConvertTo(x, typeof(byte[])); return xByte; } 

另一种从图像path获取字节数组的方法是

 byte[] imgdata = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(path)); 

尝试这个:

 public byte[] imageToByteArray(System.Drawing.Image imageIn) { MemoryStream ms = new MemoryStream(); imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif); return ms.ToArray(); } public Image byteArrayToImage(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms); return returnImage; } 

您可以使用File.ReadAllBytes()方法将任何文件读入字节数组。 要将字节数组写入文件,只需使用File.WriteAllBytes()方法即可。

希望这可以帮助。

你可以在这里find更多的信息和示例代码。

这是我目前使用的。 我尝试过的其他一些技术是非最佳的,因为它们改变了像素的位深度(24位与32位)或者忽略了图像的分辨率(dpi)。

  // ImageConverter object used to convert byte arrays containing JPEG or PNG file images into // Bitmap objects. This is static and only gets instantiated once. private static readonly ImageConverter _imageConverter = new ImageConverter(); 

图像到字节数组:

  /// <summary> /// Method to "convert" an Image object into a byte array, formatted in PNG file format, which /// provides lossless compression. This can be used together with the GetImageFromByteArray() /// method to provide a kind of serialization / deserialization. /// </summary> /// <param name="theImage">Image object, must be convertable to PNG format</param> /// <returns>byte array image of a PNG file containing the image</returns> public static byte[] CopyImageToByteArray(Image theImage) { using (MemoryStream memoryStream = new MemoryStream()) { theImage.Save(memoryStream, ImageFormat.Png); return memoryStream.ToArray(); } } 

字节数组到图像:

  /// <summary> /// Method that uses the ImageConverter object in .Net Framework to convert a byte array, /// presumably containing a JPEG or PNG file image, into a Bitmap object, which can also be /// used as an Image object. /// </summary> /// <param name="byteArray">byte array containing JPEG or PNG file image or similar</param> /// <returns>Bitmap object if it works, else exception is thrown</returns> public static Bitmap GetImageFromByteArray(byte[] byteArray) { Bitmap bm = (Bitmap)_imageConverter.ConvertFrom(byteArray); if (bm != null && (bm.HorizontalResolution != (int)bm.HorizontalResolution || bm.VerticalResolution != (int)bm.VerticalResolution)) { // Correct a strange glitch that has been observed in the test program when converting // from a PNG file image created by CopyImageToByteArray() - the dpi value "drifts" // slightly away from the nominal integer value bm.SetResolution((int)(bm.HorizontalResolution + 0.5f), (int)(bm.VerticalResolution + 0.5f)); } return bm; } 

编辑:要从JPG或PNG文件中获取图像,您应该使用File.ReadAllBytes()将文件读入一个字节数组中:

  Bitmap newBitmap = GetImageFromByteArray(File.ReadAllBytes(fileName)); 

这可以避免与Bitmap相关的问题,希望它的源码stream保持打开状态,还有一些build议的解决方法,导致源文件被locking。

你只想像素或整个图像(包括头)作为一个字节数组?

对于像素: CopyPixels图上使用CopyPixels方法。 就像是:

 var bitmap = new BitmapImage(uri); //Pixel array byte[] pixels = new byte[width * height * 4]; //account for stride if necessary and whether the image is 32 bit, 16 bit etc. bitmap.CopyPixels(..size, pixels, fullStride, 0); 

如果你没有引用imageBytes来传送stream中的字节,这个方法将不会返回任何东西。 确保你引用imageBytes = m.ToArray();

  public static byte[] SerializeImage() { MemoryStream m; string PicPath = pathToImage"; byte[] imageBytes; using (Image image = Image.FromFile(PicPath)) { using ( m = new MemoryStream()) { image.Save(m, image.RawFormat); imageBytes = new byte[m.Length]; //Very Important imageBytes = m.ToArray(); }//end using }//end using return imageBytes; }//SerializeImage 

此代码从SQLSERVER 2012中的表中检索前100行,并将每行图片保存为本地磁盘上的文件

  public void SavePicture() { SqlConnection con = new SqlConnection("Data Source=localhost;Integrated security=true;database=databasename"); SqlDataAdapter da = new SqlDataAdapter("select top 100 [Name] ,[Picture] From tablename", con); SqlCommandBuilder MyCB = new SqlCommandBuilder(da); DataSet ds = new DataSet("tablename"); byte[] MyData = new byte[0]; da.Fill(ds, "tablename"); DataTable table = ds.Tables["tablename"]; for (int i = 0; i < table.Rows.Count;i++ ) { DataRow myRow; myRow = ds.Tables["tablename"].Rows[i]; MyData = (byte[])myRow["Picture"]; int ArraySize = new int(); ArraySize = MyData.GetUpperBound(0); FileStream fs = new FileStream(@"C:\NewFolder\" + myRow["Name"].ToString() + ".jpg", FileMode.OpenOrCreate, FileAccess.Write); fs.Write(MyData, 0, ArraySize); fs.Close(); } } 

请注意:具有NewFolder名称的目录应该存在于C:\

码:

 using System.IO; byte[] img = File.ReadAllBytes(openFileDialog1.FileName);