转换一个动态的BitmapImage为灰度的BitmapImage在Windows Phone应用程序 [英] Convert a dynamic BitmapImage to a grayscale BitmapImage in a Windows Phone application

查看:271
本文介绍了转换一个动态的BitmapImage为灰度的BitmapImage在Windows Phone应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换一个BitmapImage的一个灰度的BitmapImage:这是我从一个方法,因此得到 - 宽度和高度是未知的我。我试图寻找到的选项,如WritableBitmapEx和静态扩展方法,但他们一直没对我很有帮助,因为我想返回数据类型是一个BitmapImage的,以及我那么就需要将它添加到列表。

I would like to Convert a BitmapImage to a Grayscale BitmapImage: Which I get from a method and therefore - the Width and Height are unknown to me. I have tried looking into options such as WritableBitmapEx and static extension methods but they haven't been helpful to me as I would like the return data type to be a BitmapImage as well as I then need to add it to List.

这是可能在使用C#一个Windows Phone应用程序?我真的很感激,如果有人提供一些线索到此。谢谢

Is this possible in a Windows Phone app using C#? I would really appreciate if someone would shed some light into this. Thank you.

推荐答案

算法很简单:

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






代码在行动:


Code in Action:

这篇关于转换一个动态的BitmapImage为灰度的BitmapImage在Windows Phone应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆