Create a BitmapImage from a byte array

前端 未结 2 713
滥情空心
滥情空心 2020-11-28 15:49

I am creating a byte array with arbitrary values in it and want to convert it into a BitmapImage.

    bi = new BitmapImage();
    using (MemoryStream stream          


        
相关标签:
2条回答
  • 2020-11-28 16:28

    The byte array must contain valid image data (PNG / JPG / BMP). If you remove the using-block and the data is valid then your Code should work. BitmapImage doesn't seem to load the image immediatly, so it can't load it afterwards because the stream is already disposed.

    What do you mean by "arbitrary values"? Random RGB values? Then I propose to use the Bitmap class and save the resulting Bitmap in a Memorystream.

    If you just want to bind a Byte[] to and Image Control in your userinterface: Bind directly to the array. It works without a converter.

    0 讨论(0)
  • 2020-11-28 16:39

    Given an array of bytes where each byte represents a pixel value, you may create a grayscale bitmap like shown below. You need to specify the width and height of the bitmap, and that must of course match the buffer size.

    byte[] buffer = ... // must be at least 10000 bytes long in this example
    
    var width = 100; // for example
    var height = 100; // for example
    var dpiX = 96d;
    var dpiY = 96d;
    var pixelFormat = PixelFormats.Gray8; // grayscale bitmap
    var bytesPerPixel = (pixelFormat.BitsPerPixel + 7) / 8; // == 1 in this example
    var stride = bytesPerPixel * width; // == width in this example
    
    var bitmap = BitmapSource.Create(width, height, dpiX, dpiY,
                                     pixelFormat, null, buffer, stride);
    

    Each byte value may also represent an index into a color palette, in which case your would have to specify PixelFormats.Indexed8 and of course also pass in an appropriate color palette.

    0 讨论(0)
提交回复
热议问题