3

我如何在 Windows Phone 8 中将普通图像转换为灰度图像。WritableBitmapEx 中是否有任何灰度转换的规定。

4

2 回答 2

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;
}
于 2013-04-10T14:00:43.833 回答
2

我不认为有一种方法,但你可以自己转换它。网上有很多关于如何做到这一点的资源。从阅读本文开始。一种更简单的方法可能是:

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;
}

它简单、快速,并且您可以就地转换它。

于 2013-04-10T13:55:46.697 回答