【发布时间】:2015-09-03 19:34:40
【问题描述】:
我在 WPF 应用程序中搞乱位图。我在后台线程上收到一个字节数组,转换器将其更改为 bitmapSource 以进行绑定。
但是,如果我尝试直接在内存中创建 bitmapSource 并显示它,它会将图像一分为二。我没有丰富的位图经验,但足以让我始终显示图像。
奇怪的是,如果我先写出文件,然后再读回,它就可以工作。
File.WriteAllBytes(@"C:\woot2.bmp", bytes);
var bmp = new BitmapImage(new Uri(@"C:\woot2.bmp"));
var height = bmp.Height; // 480.0
var width = bmp.Width; // 640.0
var format = bmp.Format; // Indexed8
var dpix = bmp.DpiX; // 96.0
var dpiY = bmp.DpiY; // 96.0
var pallete = bmp.Palette; // Gray256
var cacheOption = bmp.CacheOption; // Default
var createOptions = bmp.CreateOptions; // None
return bmp;
[
我检查了高度、宽度、pixelFormat、pixelPalette、dpi 等都与我读入的文件匹配,但它仍然显示不正确。甚至检查了文件的标题。
我已经使用 PngBitmapEncoder 尝试了 BitmapImages、BitmapSources、WriteableBitmaps,但我仍然得到相同的结果。我觉得要么我错过了一些基本的东西,要么有一个错误。我以为切片是错误的,但没有歪斜,
我在图片中显示它:
<Image Width="640" Height="480"
Source="{Binding VisionImage, Mode=OneWay,UpdateSourceTrigger=PropertyChanged,
Converter={StaticResource VisionImageConverter} }"></Image>
这是我目前必须转换的代码
var width = 640;
var height = 480;
var dpiX = 96;
var dpiY = 96;
var pixelFormat = PixelFormats.Indexed8;
var palleteFormat = BitmapPalettes.Gray256;
var stride = 4* (((width*pixelFormat.BitsPerPixel) + 31)/32);
return BitmapSource.Create(width, height, dpiX, dpiY,
pixelFormat, palleteFormat, bytes, stride);
有什么想法吗?
【问题讨论】:
-
如果问题是关于传递给
bytes的File.WriteAllBytes(@"C:\woot2.bmp", bytes);,那么您有一个编码的BMP 缓冲区,而不是原始像素缓冲区。您不应使用它调用 BitmapSource.Create。而是从字节数组创建一个 MemoryStream 并将其分配给 BitmapImage 的StreamSource属性。 -
我也试过位图图像(这肯定是 new BitmapImage(new Uri("....")) 使用的,只是原始字节?
-
顺便说一句,你的步幅公式是错误的,应该是
bytesPerPixel = (bitsPerPixel + 7) / 8然后是stride = width * bytesPerPixel。 -
嗯,真的吗?看到这个公式在很多地方都使用过,而且它最终是 640,对于我的文件大小来说,每个像素一个字节应该是正确的