在Windows Phone 8中将图像转换为灰度

时间:2013-04-10 13:36:49

标签: windows-phone-7 windows-phone-8

如何在Windows Phone 8中将普通图像转换为灰度图像。在WritableBitmapEx中是否提供了灰度转换。

2 个答案:

答案 0 :(得分:8)

try this extension method...

public static WriteableBitmap ToGrayScale(this 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;
}

答案 1 :(得分:1)

我不认为有一种方法,但你可以自己转换它。有很多关于如何实现这一目标的在线资源。首先阅读this。其中一个更简单的方法可能是:

for (int i = 0; i < oldBitmap.Pixels.Length; i++)
{
    var c = oldBitmap.Pixels[i];
    var a = (byte)(c >> 24);
    var r = (byte)(c >> 16);
    var g = (byte)(c >> 8);
    var b = (byte)(c);

    byte gray = (byte)((r * 0.3) + (g * 0.59) + (b * 0.11));
    oldBitmap.Pixels[i] = (a << 24) | (gray << 16) | (gray << 8) | gray;
}

它简单,快速,您可以就地进行转换。