Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

wpf - Create a BitmapImage from a byte array

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 = new MemoryStream(data))
    {
      try
      {
        bi.BeginInit();
        bi.CacheOption = BitmapCacheOption.OnLoad;
        bi.StreamSource = stream;
        bi.DecodePixelWidth = width;

        bi.EndInit();

      }
      catch (Exception ex)
      {
        return null;
      }
    }

This code gives me a NotSupportedException all the time. How could I create a BitmapSource from any byte array?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...