Convert a dynamic BitmapImage to a grayscale BitmapImage in a Windows Phone application

后端 未结 3 757
误落风尘
误落风尘 2021-01-24 01:14

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 opt

3条回答
  •  醉梦人生
    2021-01-24 01:33

    The Algorithm is pretty simple:

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

    
    

    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:

    enter image description here

提交回复
热议问题