Using Alpha when Manipulating Images

I'm trying to get an image to display with one of the colors replaced with a white alpha so I can stack it on top of the other images. I have it so that I can easily change colors, but changing its transparency eludes 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 have two images that I am testing this with. Image1 is similar to what I will be working on, with no transparency in the original image. Image2 already has transparency. I thought it would be easy to just get the value from image2 (0x00ffffff), but that just makes it white and covers any images.

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

Does anyone know how to make an image transparent?

+2


source to share


1 answer


How about using Bgra32 ?



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

+3


source







All Articles