BitmapImage转换为byte

BitmapImage转换为byte

本文介绍了WPF BitmapImage转换为byte []时出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在将BitmapImage保存到一个byte []中以保存在数据库中.我很确定数据可以准确地保存和检索,所以这不是问题.

I'm saving a BitmapImage to a byte[] for saving in a DB. I'm pretty sure the data is being saved and retrieved accurately so it's not an issue there.

在我的将byte []转换为BitmapImage的过程中,我不断遇到"System.NotSupportedException:未找到适合完成此操作的成像组件"的异常.

On my byte[] to BitmapImage conversion I keep getting an exception of "System.NotSupportedException: No imaging component suitable to complete this operation was found."

有人可以在这里看到我的两个功能在做什么吗?

Can anyone see what I'm doing wrong with my two functions here?

  private Byte[] convertBitmapImageToBytestream(BitmapImage bi)
  {
     int height = bi.PixelHeight;
     int width = bi.PixelWidth;
     int stride = width * ((bi.Format.BitsPerPixel + 7) / 8);

     Byte[] bits = new Byte[height * stride];
     bi.CopyPixels(bits, stride, 0);

     return bits;
  }

  public BitmapImage convertByteToBitmapImage(Byte[] bytes)
  {
     MemoryStream stream = new MemoryStream(bytes);
     stream.Position = 0;
     BitmapImage bi = new BitmapImage();
     bi.BeginInit();
     bi.StreamSource = stream;
     bi.EndInit();
     return bi;
  }

推荐答案

结果证明,位图图像CopyPixels不正确.我将bitmapimage的输出转换为可用的图片(在这种情况下为jpg).

Turns out the bitmapimage CopyPixels isn't right. I take the output of the bitmapimage and convert it to something usable in this case a jpg.

public static Byte[] convertBitmapImageToBytestream(BitmapImage bi)
  {
     MemoryStream memStream = new MemoryStream();
     JpegBitmapEncoder encoder = new JpegBitmapEncoder();
     encoder.Frames.Add(BitmapFrame.Create(bi));
     encoder.Save(memStream);
     byte[] bytestream = memStream.GetBuffer();
     return bytestream;
  }

这篇关于WPF BitmapImage转换为byte []时出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 01:25