簡體   English   中英

在Windows Phone應用程序中將動態BitmapImage轉換為灰度BitmapImage

[英]Convert a dynamic BitmapImage to a grayscale BitmapImage in a Windows Phone application

我想將BitmapImage轉換為灰度BitmapImage:從方法中獲取,因此-寬度和高度對我來說是未知的。 我嘗試研究諸如WritableBitmapEx和靜態擴展方法之類的選項,但它們對我沒有幫助,因為我希望返回數據類型為BitmapImage,然后再將其添加到List中。

使用C#的Windows Phone應用程序中是否可能? 如果有人能對此有所啟發,我將不勝感激。 謝謝。

不確定此處的命名空間,但類似的方法可能起作用:

using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

FormatConvertedBitmap bitmapGreyscale = new FormatConvertedBitmap(bitmap, PixelFormats.Gray8, BitmapPalettes.Gray256, 0.0);

該算法非常簡單:

using System.Windows.Media.Imaging;
using System.IO;

private WriteableBitmap ConvertToGrayScale(BitmapImage source)
{
    WriteableBitmap wb = new WriteableBitmap(source);               // create the WritableBitmap using the source

    int[] grayPixels = new int[wb.PixelWidth * wb.PixelHeight];

    // lets use the average algo 
    for (int x = 0; x < wb.Pixels.Length; x++)
    {
        // get the pixel
        int pixel = wb.Pixels[x];

        // get the component
        int red = (pixel & 0x00FF0000) >> 16;
        int blue = (pixel & 0x0000FF00) >> 8;
        int green = (pixel & 0x000000FF);

        // get the average
        int average = (byte)((red + blue + green) / 3);

        // assign the gray values keep the alpha
        unchecked
        {
            grayPixels[x] = (int)((pixel & 0xFF000000) | average << 16 | average << 8 | average);
        }
    }



    // copy grayPixels back to Pixels
    Buffer.BlockCopy(grayPixels, 0, wb.Pixels, 0, (grayPixels.Length * 4));

    return wb;            
}

private BitmapImage ConvertWBtoBI(WriteableBitmap wb)
{
    BitmapImage bi;
    using (MemoryStream ms = new MemoryStream())
    {
        wb.SaveJpeg(ms, wb.PixelWidth, wb.PixelHeight, 0, 100);
        bi = new BitmapImage();
        bi.SetSource(ms);
    }
    return bi;
}

<Image x:Name="myImage" Source="/Assets/AlignmentGrid.png" Stretch="None" />

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{       
    WriteableBitmap wb = ConvertToGrayScale((BitmapImage)this.myImage.Source);
    BitmapImage bi = ConvertWBtoBI(wb);


    myImage.Source = bi;       
}

實際代碼:

在此處輸入圖片說明

您無法寫入BitmapImage:您需要將其轉換為WriteableBitmap。 一旦有了WriteableBitmap,就可以輕松訪問緩沖區並將像素轉換為GreyScale。

由於WriteableBitmaps和BitmapImages都是BitmapSource,因此兩者的工作方式非常相似。 如果您將列表創建為列表而不是列表,則可以將它們添加到同一列表中

該應用程序不太可能對列表的內容執行任何操作,這些內容要求內容為BitmapImages而不是BitmapSources。

暫無
暫無

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

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