-1

I want to change some pixels of an image. The image build action is set to "Resource". I'm not possible to get a Bitmap object, so I can make my changes with the for loop below.

        Bitmap bmp = new Bitmap("pack://application:,,,/ovl_kommen.png");


        //Change Black pixels to color
        for (int x = 0; x < bmp.Width; x++)
        {
            for (int y = 0; y < bmp.Height; y++)
            {
                if (bmp.GetPixel(x,y) == System.Drawing.Color.Black)
                {
                    bmp.SetPixel(x, y, System.Drawing.Color.Blue);
                }
            }
        }

My next problem is, to view the modified bitmap to an user. I have a WPF image control img_kommen which I want to set the bitmap as source. img_kommen.Source = bmp

Il Vic
  • 5,576
  • 4
  • 26
  • 37
Joba
  • 828
  • 9
  • 28
  • 1
    System.Drawing.Bitmap is WinForms, not WPF. You would usually not use it in WPF application. – Clemens Sep 26 '17 at 08:09
  • Whats the WPF equivalent? – Joba Sep 26 '17 at 08:10
  • It's BitmapImage. There also is WriteableBitmap, which allows to modify the pixel buffer. – Clemens Sep 26 '17 at 08:11
  • Is there any guide/example how to set/getPixel colors of an BitmapImage? – Joba Sep 26 '17 at 08:20
  • Why would you want to do that all, instead of just editing the image before using it as a resource? – Clemens Sep 26 '17 at 08:34
  • It's a simple black icon with transparent background. When the user selects red as foreground, the icon needs to change its black pixels to red. – Joba Sep 26 '17 at 08:42
  • 1
    WPF provides better ways to accomplish that. You may for example use a Path instead of an Image control, and have a Geometry for the Icon shape. Or put the image into an ImageBrush that is used as the OpacityMask of a Rectangle with an appropriate Fill (i.e. black or red). – Clemens Sep 26 '17 at 08:47
  • Or simply use two different image resources, one black and one red. – Clemens Sep 26 '17 at 08:48

1 Answers1

1

Instead of manipulating pixel values, better simply use a filled Rectangle and apply your icon image as OpacityMask, because

This property only uses whatever the alpha channel value is for the supplied Brush. The other channels of the Brush's rendered content (Red, Green, or Blue) are ignored

Example:

<Rectangle x:Name="icon" Fill="Black" Width="100" Height="100">
    <Rectangle.OpacityMask>
        <ImageBrush ImageSource="ovl_kommen.png" Stretch="Uniform"/>
    </Rectangle.OpacityMask>
</Rectangle>

Then set the icon color in code behind like:

icon.Fill = Brushes.Red;
Clemens
  • 123,504
  • 12
  • 155
  • 268