3

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

在我的 byte[] 到 BitmapImage 的转换中,我不断收到“System.NotSupportedException:找不到适合完成此操作的成像组件”的异常。

谁能看到我在这里的两个功能做错了什么?

  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;
  }
4

3 回答 3

0

这个 StackOverflow 问题有帮助吗?

Silverlight 中的 byte[] 到 BitmapImage

编辑:

试试这个,不确定它是否有效:

public BitmapImage convertByteToBitmapImage(Byte[] bytes)
{
    MemoryStream stream = new MemoryStream(bytes);
    stream.Position = 0;
    BitmapImage bi = new BitmapImage();
    bi.BeginInit();
    bi.CacheOption = BitmapCacheOption.OnLoad;
    bi.DecodePixelWidth = ??; // Width of the image
    bi.StreamSource = stream;
    bi.EndInit();
    return bi;
}

更新 2:

我发现了这些:

在运行时将 byte[] 加载到图像中

来自非 UIThread 上的 byte[] 的 BitmapImage

除此之外,我不知道。

于 2010-10-08T00:38:33.050 回答
0

你怎么知道你正在创建的 byte[] 格式是 BI 在 Stream 中所期望的?为什么不使用 BitmapImage.StreamSource 来创建您保存的 byte[]?然后你知道格式将是兼容的。

http://www.codeproject.com/KB/vb/BmpImage2ByteArray.aspx

http://social.msdn.microsoft.com/forums/en-US/wpf/thread/8327dd31-2db1-4daa-a81c-aff60b63fee6/

[我没有尝试任何这段代码,但你可以]

于 2010-10-08T18:44:51.177 回答
0

原来位图图像 CopyPixels 不正确。我获取位图图像的输出并将其转换为在这种情况下可用的 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;
  }
于 2010-10-08T23:31:53.707 回答