Error in my byte [] for WPF BitmapImage conversion?

I am saving BitmapImage in bytes [] to save to the DB. I am sure that the data is saved and retrieved accurately, so this is not a problem.

In my byte [] for BitmapImage conversion, I always get an exception from "System.NotSupportedException: the image component was not found suitable for completing this operation."

Can anyone see what I am 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;
  }
+3
source share
3 answers

Turns off bitmapimage CopyPixels incorrectly. I accept the output of bitmapimage and convert it to something suitable for use in this case 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;
  }
0

StackOverflow?

byte [] BitmapImage silverlight

EDIT:

, , :

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:

:

[]

BitmapImage from byte [] UIThread

, .

0

Source: https://habr.com/ru/post/1768534/


All Articles