views:

32

answers:

3

Hello!

I've edited an bitmap in c# and for every pixel i've changed it to a certain color if a condition was true else i've set the color to Color.Transparent ( the operations were done with getPixel/setPixel ) . I've exported the image in .png format but the image isn't transparent. Any ideas why or how should i do it ?

Regards, Alexandru Badescu

here is the code : -- here i load the image and convert to PixelFormat.Format24bppRgb if png

m_Bitmap = (Bitmap)Bitmap.FromFile(openFileDialog.FileName, false);

           if(openFileDialog.FilterIndex==3) //3 is png
            m_Bitmap=ConvertTo24(m_Bitmap);

-- this is for changing the pixels after a certain position in an matrix

for (int i = startX; i < endX; i++)

                for (int j = startY; j < endY; j++)
                {
                    if (indexMatrix[i][j] == matrixFillNumber)
                        m_Bitmap.SetPixel(j, i, selectedColor);
                    else
                        m_Bitmap.SetPixel(j, i, Color.Transparent);

                }
A: 

I will need more code to verify, but my best guess is that you first write something on the bitmap to clear it (like fill it with White color), then to make the transparent pixels you draw with Color.Transparent on top. This will simply not work, since White (or anything else) with Transparent on top, is still White.

Øyvind Bråthen
code has been added
Badescu Alexandru
A: 

If you have created a bitmap in code, it will be most likely 24 bit and would not support alpha blending/transparent.

provide the code for creating and we should be able to help.

Aliostad
code has been added
Badescu Alexandru
+2  A: 

Its because pixelformat. Here is a sample code for you:

        Bitmap inp = new Bitmap("path of the image to edit");
        Bitmap outImg = new Bitmap(inp.Width, inp.Height, PixelFormat.Format32bppArgb);
        outImg.SetResolution(inp.HorizontalResolution, inp.VerticalResolution);
        Graphics g = Graphics.FromImage(outImg);
        g.DrawImage(inp, Point.Empty);
        g.Dispose();
        inp.Dispose();

        ////
        // Check your condition and set pixel here (outImg.GetPixel, outImg.SetPixel)
        ////

        outImg.Save("out file path", ImageFormat.Png);
        outImg.Dispose();

this is the code that requires minimum change to your current code. But i would recommend you to check out LockBits Method for a better performance: http://msdn.microsoft.com/en-us/library/5ey6h79d.aspx

honibis
I havnt tested it but this should work. So here goes my +1.
Aliostad
ah so formats below format32bppArgb do not work?
Badescu Alexandru
@Badescu You absolutely need alpha for bitmap transparency.
honibis
Thanks a lot!!!!!
Badescu Alexandru
if i change to pixelFormat.Format32bppArgb, wouldn't the image be smaller?
Badescu Alexandru