繁体   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