2015-07-22 26 views
0

我有一個WriteableBitmap圖像,我只想在buttonclick事件中僅顯示它的綠色組件。在可寫位圖圖像中僅顯示ARGB中的綠色組件顏色

早些時候我試圖先把它轉換成灰度,然後我希望能在這之後只顯示綠色組件,但無論如何我都無法破解它。

下面就是我目前正在爲將圖像轉換爲灰度圖像的代碼:

public static WriteableBitmap ToGrayScale(WriteableBitmap bitmapImage) { 

    for (var y = 0; y < bitmapImage.PixelHeight; y++) { 
     for (var x = 0; x < bitmapImage.PixelWidth; x++) { 
      var pixelLocation = bitmapImage.PixelWidth * y + x; 
      var pixel = bitmapImage.Pixels[pixelLocation]; 
      var pixelbytes = BitConverter.GetBytes(pixel); 
      var bwPixel = (byte)(.299 * pixelbytes[2] + .587 * pixelbytes[1] + .114 * pixelbytes[0]); 
      pixelbytes[0] = bwPixel; 
      pixelbytes[1] = bwPixel; 
      pixelbytes[2] = bwPixel; 
      bitmapImage.Pixels[pixelLocation] = BitConverter.ToInt32(pixelbytes, 0); 
     } 
    } 

    return bitmapImage; 
} 

我收到此錯誤: 「Windows.UI.Xaml.Media.Imaging.WriteableBitmap」呢不包含'像素'的定義,也沒有擴展方法'像素'接受類型'Windows.UI.Xaml.Media.Imaging.WriteableBitmap'的第一個參數可以找到(你是否缺少using指令或程序集引用?)

有些幫助會非常感謝我。謝謝。

回答

0

你要複製圖像的第二通道。

public static WriteableBitmap ToGrayScale(WriteableBitmap bitmapImage) { 

    for (var y = 0; y < bitmapImage.PixelHeight; y++) { 
     for (var x = 0; x < bitmapImage.PixelWidth; x++) { 
      var pixelLocation = bitmapImage.PixelWidth * y + x; 
      var pixel = bitmapImage.Pixels[pixelLocation]; 
      var pixelbytes = BitConverter.GetBytes(pixel); 
      var greenChannel = (byte)(pixelbytes[1]); 
      pixelbytes[0] = greenChannel; 
      pixelbytes[1] = greenChannel; 
      pixelbytes[2] = greenChannel; 
      bitmapImage.Pixels[pixelLocation] = BitConverter.ToInt32(pixelbytes, 0); 
     } 
    } 

    return bitmapImage; 
} 

(在這段代碼中,我假設你的灰色轉換是正確的Windows具有存儲RGB圖像作爲BGR在內存中的趨勢我。我不確定alpha通道的位置,你應該檢查一下測試圖像,它有純色區域。)

+0

bitmapImage.Pixels [pixelLocation] = BitConverter.ToInt32(pixelbytes,0);我在這條線上面臨着問題,沒有像素的參考。 –

+0

對不起,我忽略了。如果你的灰度轉換不起作用,你能否用錯誤信息更新你的問題? –

+0

最有可能的是,你的問題是你正在轉換爲'Int32'。像素值通常是「uint8」。但我不熟悉C# –

0

如上所述,Windows.UI.Xaml.Media.Imaging.WriteableBitmap沒有像素屬性:它有一個PixelBuffer,它將像素作爲IBuffer返回。

可以使用DataReader & DataWriter或通過與AsStream擴展方法,或轉換爲流以一個字節[]與ToArray擴展方法訪問IBuffer。一旦你有一個流或數組,它很容易循環,將字節轉換爲綠色或灰度,並將修改的像素設置回來。

我的同事傑夫證明在他的博客中How to: Convert an Image to Grayscale

開源WriteableBitmapEx項目也增加了自己的擴展WriteableBitmap的訪問PixelBuffer通過AsStream灰度轉換。

+0

: [如何:將圖像轉換爲灰度],此鏈接給我灰度圖像。可以請告訴我,我需要做些什麼改變才能獲取圖像的綠色部分?實際上這非常慢,你有什麼想法如何優化這個算法? –