从字节数组创建 BitmapImage [英] Create a BitmapImage from a byte array

查看:31
本文介绍了从字节数组创建 BitmapImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个包含任意值的字节数组,并希望将其转换为 BitmapImage.

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

这段代码一直给我一个 NotSupportedException.如何从任何字节数组创建 BitmapSource?

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

推荐答案

给定一个字节数组,其中每个字节代表一个像素值,您可以创建如下所示的灰度位图.您需要指定位图的宽度和高度,当然必须与缓冲区大小匹配.

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);

<小时>

每个字节值也可能代表调色板的索引,在这种情况下,您必须指定PixelFormats.Indexed8,当然还要传入适当的调色板.


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.

这篇关于从字节数组创建 BitmapImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆