views:

82

answers:

2

Hi,

I have a JPEG format image, with a white background and a black circle.

How can I transform this image to a PNG format that the white background will be transparent and the black remains there?

I'm a programmer too, and if there are some ideas in C# code I will be very happy. Also I'm looking for a converter, tool, program anything.

Thank you.

Jeff

+1  A: 

You could use the ImageMagick tool like this example.

You will need to set the -background option to transparent, set the the -alpha option to set and use the -transparent option to set the colour you want to be interpretted as transparent. See also the convert tool reference.

Paul Ruane
+2  A: 

Here is working, but slow solution. You can speed it up by using Bitmap.LockBits().

using (Image img = Image.FromFile(filename))
using (Bitmap bmp = new Bitmap(img))
{
    for (int x = 0; x < img.Width; x++)
    {
        for (int y = 0; y < img.Height; y++)
        {
            Color c = bmp.GetPixel(x, y);
            if (c.R == 255 && c.G == 255 && c.B == 255)
                bmp.SetPixel(x, y, Color.FromArgb(0));
        }
    }
    bmp.Save("out.png", ImageFormat.Png);
}
ironic
hmm, what should I import to use 'Image', 'Bitmap' and 'Color'?
Jeff Norman
You will need to reference System.Drawing.dll
ironic
Yes, it was such a fullish question of mine...
Jeff Norman
ok, the code it's working fine.... my next question is: how do I know that my image has a really transparent background?
Jeff Norman
This is definitely not a programmers approach, but I would use color pick tool in Paint.NET to check :)
ironic
thanks a lot :)
Jeff Norman
If this solution is too slow, it may be because `GetPixel` adds an extra layer of indirection. Using `unsafe` code via pointers is likely faster, if necessary. See http://www.codeproject.com/KB/GDI-plus/csharpgraphicfilters11.aspx for examples, though you'll need to adapt them for your purposes.
Brian
@Jeff, glad to help!
ironic