Question

I'm trying to get an image to display with one of the colors replaced with a white alpha so that I can layer it on top of other images. I've got it so that I can change colors easily enough, but changing it to be transparent is eluding me. Here's my code, using C# and WPF.

    private void SetAlpha(string location)
    {
        //bmp is a bitmap source that I load from an image
        bmp = new BitmapImage(new Uri(location));
        int[] pixels = new int[(int)bmp.Width * (int)bmp.Height];
        //still not sure what 'stride' is.  Got this part from a tutorial
        int stride = (bmp.PixelWidth * bmp.Format.BitsPerPixel + 7)/8;

        bmp.CopyPixels(pixels, stride, 0);
        int oldColor = pixels[0];
        int red = 255;
        int green = 255;
        int blue = 255;
        int alpha = 0;
        int color = (alpha << 24) + (red << 16) + (green << 8) + blue;

        for (int i = 0; i < (int)bmp.Width * (int)bmp.Height; i++)
        {
            if (pixels[i] == oldColor)
            {
                pixels[i] = color;
            }
        }
            //remake the bitmap source with these pixels
            bmp = BitmapSource.Create(bmp.PixelWidth, bmp.PixelHeight, bmp.DpiX, bmp.DpiY, bmp.Format, bmp.Palette, pixels, stride);
        }

    }

I've got two images that I'm testing this with. Image1 is like what I am going to be working on, no transparency in the original image. Image2 already has transparency. I thought it would be easy to just grab the value from image2 (0x00ffffff) but that just makes it white and covers up any images behind.

Both images are png, and the format for both is Bgr32.

Does anyone know how to get the image to be transparent?

Was it helpful?

Solution

How about using Bgra32?

Also make sure you understand how the color is represented in memory and what alpha means.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top