WPF中把图片变成灰色
2010年7月8日
分类: WPF
在WPF中如何将一张彩色图片变成灰色的,可以用WPF给我们的bitmap转换器完成,或者使用算法将彩色的rgb转化成灰色rgb。这种效果用的地方很多,比如QQ头像离线时头像会变成灰色。
下面我们看一下代码:
第一种:
FormatConvertedBitmap bitmap = new FormatConvertedBitmap(); bitmap.BeginInit(); bitmap.Source = (BitmapSource)source; bitmap.DestinationFormat = PixelFormats.Gray32Float; bitmap.EndInit(); return bitmap;
第二种:
BitmapSource sourceImage = (BitmapSource)source;
byte[] orgPixels = new byte[sourceImage.PixelHeight * sourceImage.PixelWidth * 4];
byte[] newPixels = new byte[orgPixels.Length];
sourceImage.CopyPixels(orgPixels, sourceImage.PixelWidth * 4, 0);
for (int i = 3; i < orgPixels.Length; i += 4)
{
int grayVal = ((int)orgPixels[i - 3] +
(int)orgPixels[i - 2] + (int)orgPixels[i - 1]);
if (grayVal != 0)
grayVal = grayVal / 3;
newPixels[i] = orgPixels[i]; //Set AlphaChannel
newPixels[i - 3] = (byte)grayVal;
newPixels[i - 2] = (byte)grayVal;
newPixels[i - 1] = (byte)grayVal;
}
return BitmapSource.Create(sourceImage.PixelWidth, sourceImage.PixelHeight, 96, 96, PixelFormats.Bgra32, null, newPixels, sourceImage.PixelWidth * 4);
从上面两种方式都会返回灰阶的ImageSource对象,不难看出,第一种要简单的多,使用wpf内置FormatConvertedBitmap类进行图像格式转换,要方便的多,同时也给我们提供了非常丰富的转换格式,通过设置DestinationFormat属性就可以方便的将图像转换成各种格式。
原创文章,转载请注明: 转载自.NET开发者
本文链接地址: WPF中把图片变成灰色
Related posts:
呵呵,很好很强大