【问题标题】:error in my byte[] to WPF BitmapImage conversion?我的 byte[] 到 WPF BitmapImage 转换中的错误?
【发布时间】:2010-10-08 00:15:50
【问题描述】:

我将 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;
  }

【问题讨论】:

    标签: wpf bytearray byte bitmapimage


    【解决方案1】:

    这个 StackOverflow 问题有帮助吗?

    byte[] to BitmapImage in silverlight

    编辑:

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

    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:

    我找到了这些:

    Load a byte[] into an Image at Runtime

    BitmapImage from byte[] on a non UIThread

    除此之外,我不知道。

    【讨论】:

      【解决方案2】:

      您如何知道您正在创建的 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/

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

      【讨论】:

        【解决方案3】:

        原来位图图像 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;
          }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多