我想将位图图像转换为灰度位图图像:这是我从方法中获得的,因此 - 宽度和高度对我来说是未知的。我尝试过研究 WritableBitmapEx 和静态扩展方法等选项,但它们对我没有帮助,因为我希望返回数据类型为 BitmapImage,然后需要将其添加到列表中。
在使用 C# 的 Windows Phone 应用程序中这可能吗?如果有人能对此有所启发,我将非常感激。谢谢。
该算法非常简单:
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;
}
实际代码:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)