开发者

export transparent images in c#?

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(openF开发者_运维技巧ileDialog.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);

                }


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜