Make a color transparent in a gif, jpg, bmp? Its black!


C

Chris Auer

I have been banging my head for a couple of hours now. No matter what I
do the color that I make transparent is black. Here is the code I am
using from MSDN. I have tried bitmaps, jpegs, gifs and new bitmaps
created in code, but I cant get any image to go transparent. Thanks if
you can help.


// Create a Bitmap object from an image file.
Bitmap myBitmap = new
Bitmap(System.Web.HttpContext.Current.Server.MapPath("resources/img/")
+ "\\Icons\\blank.bmp");

// Draw myBitmap to the screen.
Graphics g;
g = Graphics.FromImage(myBitmap);
g.DrawImage(
myBitmap,
0,
0,
myBitmap.Width,
myBitmap.Height);

// Get the color of a background pixel.
Color backColor = myBitmap.GetPixel(1, 1);

// Make backColor transparent for myBitmap.
myBitmap.MakeTransparent(backColor);

// Draw the transparent bitmap to the screen.
g.DrawImage(
myBitmap,
myBitmap.Width,
0,
myBitmap.Width,
myBitmap.Height);
 
Ad

Advertisements

G

Guest

g.DrawImage() in this case is not drawing the picture out to the screen, it
is drawing to the graphics instance g that is based on the bitmap you
initially loaded in.

If you wanted to save the image back for instance, than you would simply
need to do a myBitmap.Save() (with the proper arguments to save it to a
format that supports transparency).

To test it, drop your code into a Windows Forms application and drop a
picture box on the form and right after your code, throw in:
pictureBox1.Image = myBitmap to use the bitmap you have modified.

I get the suspicion that you are using this in an ASP.NET Web Form... which
if that is the case, you will have to find another mechanism to display the
image to the form as the main Web Form itself is incapable of generating and
displaying images in a way similar to using a PictureBox with a Windows Form.

If you do not want to save the image elsewhere, one option is to build a
very simple Web Form that actual draws the image and is referenced the same
way you would a regular static image from your main Web Form.

Brendan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top