-4

I'm currently working on a project (c# WPF) where I have a png that has a black figure, everything else is just transparent.

What I want to do is just change the color of the black pixels. I want to decide the color as input for the method. Right now just changing the pixels would nice. Maybe I'm in the wrong mindset when it comes to the loop (it makes everything green atm).

I tried to scour the web to find a solution that works.

What I have done is take out the pixels from a writeable bitmap. See code below.

If you guys figure it out it would save my day :)

  private void ChangeColor()
    {
        var projectPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
        string filePath = System.IO.Path.Combine(projectPath, "Resources");

        BitmapImage img = new BitmapImage(new Uri(filePath + @"\Vogn1.png", UriKind.Relative));

        WriteableBitmap myBitmap = new WriteableBitmap(img);

        int stride = myBitmap.PixelWidth * 4;
        int size = myBitmap.PixelHeight * stride;
        byte[] pixels = new byte[size];
        myBitmap.CopyPixels(pixels, stride, 0);
        int iDex = 0;
        bool black = false;

        for (int i = 0; i < pixels.Length; i++)
        {
            //if(pixels[i] == 255)

            if (iDex == 1 || iDex == 3)
                pixels[i] = 255;
            else
                pixels[i] = 0;
            iDex++;

            if (iDex == 4)
                iDex = 0;
        }

        myBitmap.WritePixels(new Int32Rect(0, 0, myBitmap.PixelWidth, myBitmap.PixelHeight), pixels, stride, 0);

        Wagon15.Source = myBitmap;
    }
SynozeN Technologies
  • 1,337
  • 1
  • 14
  • 19

1 Answers1

1

You are making it harder for yourself by looping through every byte individually. Instead, loop through every 4 bytes so that you are manipulating all the bytes of a pixel at once.

for (int i = 0; i < pixels.Length; i += 4)
{
    if (   pixels[i]   == 0 
        && pixels[i+1] == 0 
        && pixels[i+2] == 0) // All Black
    {
        pixels[i]   = 255; // Blue
        pixels[i+1] = 255; // Green
        pixels[i+2] = 255; // Red
    }
}
Abion47
  • 22,211
  • 4
  • 65
  • 88
  • Yea okay. Thanks! :) What is the alpha? What is it used for? – IstBarP - Patrick May 11 '17 at 10:28
  • @IstBarP-Patrick You wrote "i have a png that has a black figure, everything else is just transparent". Did you ever think about how that might work in terms of pixel values? – Clemens May 11 '17 at 10:31
  • @IstBarP-Patrick Alpha is the transparency level for the pixel, where 0 is fully transparent and 255 is fully opaque. – Abion47 May 11 '17 at 10:32