簡體   English   中英

WPF BitmapImage分為兩部分

[英]WPF BitmapImage sliced in two

我在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;

[ 正確的圖像[1]

我檢查了高度,寬度,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);

有任何想法嗎?

顯然,字節數組不包含原始像素數據,而是一個經過編碼的BMP緩沖區,因此您不能通過BitmapSource.Create創建一個BitmapSource.Create

您應該改為從編碼的BMP緩沖區創建BitmapImage,如下所示:

var bitmapImage = new BitmapImage();
using (var stream = new MemoryStream(bytes))
{
    bitmapImage.BeginInit();
    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
    bitmapImage.StreamSource = stream;
    bitmapImage.EndInit();
}

或者創建一個BitmapFrame像這樣:

BitmapFrame bitmapFrame;
using (var stream = new MemoryStream(bytes))
{
    bitmapFrame = BitmapFrame.Create(stream,
        BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}

好的,因此答案很簡單。 我沒有給它僅像素數組,而是給了它整個位圖文件數組。 我認為從文件創建bitmapImage時,必須在內部使用bitmapDecoder。 這就是為什么寫入文件然后將其讀回的原因。

因此我可以計算出文件中的像素偏移量,然后復制所需的字節,但是我選擇將數組包裝在內存流中並使用BmpBitmapDecoder,因為它更簡單

using(var ms = new MemoryStream(bytes))
{
     var decoder = new BmpBitmapDecoder(ms, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnDemand);
     return new WriteableBitmap(decoder.Frames.FirstOrDefault());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM