I'm trying to create an image with a transparent background to display on a web page.
I've tried several techniques but the background is always black.
How can I create a transparent image and then draw some lines on it ?
views:
2412answers:
2
+6
A:
Call Graphics.Clear(Color.Transparent)
to, well, clear the image. Don't forget to create it with a pixel format that has an alpha channel, e.g. PixelFormat.Format32bppArgb
. Like this:
var image = new Bitmap(135, 135, PixelFormat.Format32bppArgb);
using (var g = Graphics.FromImage(image)) {
g.Clear(Color.Transparent);
g.DrawLine(Pens.Red, 0, 0, 135, 135);
}
Assumes you're using
System.Drawing
and System.Drawing.Imaging
.
Edit: Seems like you don't actually need the Clear()
. Just creating the image with an alpha channel creates a blank (fully transparent) image.
OregonGhost
2009-04-02 09:00:21
I guess I missed the overload on the Bitmap constructor. Unfortunately, I don't have the code available right now, I'll try this evening...
Julien Poulin
2009-04-02 09:15:58
Trust me, it works, I tried it ;)
OregonGhost
2009-04-02 12:03:05
There was a little more than what you said to it, but I did a little research and got it to work. Thanks.
Julien Poulin
2009-04-02 18:08:01
There was really more? I did exactly what you see in my code sample and it rendered fine with alpha channel.
OregonGhost
2009-04-03 08:10:35
The *more* had nothing to do with gdi. In fact, I'm using this to render an image to an ASP.Net page. The problem was that I was saving the image (in png format) directly into the response stream, but that doesn't work for pngs, I had to save it into a memory stream first.
Julien Poulin
2009-05-16 12:01:12
A:
This might help(something I threw together which sets the background of a Windows form to a transparent image:
private void TestBackGround()
{
// Create a red and black bitmap to demonstrate transparency.
Bitmap tempBMP = new Bitmap(this.Width, this.Height);
Graphics g = Graphics.FromImage(tempBMP);
g.FillEllipse(new SolidBrush(Color.Red), 0, 0, tempBMP.Width, tempBMP.Width);
g.DrawLine(new Pen(Color.Black), 0, 0, tempBMP.Width, tempBMP.Width);
g.DrawLine(new Pen(Color.Black), tempBMP.Width, 0, 0, tempBMP.Width);
g.Dispose();
// Set the transparancy key attributes,at current it is set to the
// color of the pixel in top left corner(0,0)
ImageAttributes attr = new ImageAttributes();
attr.SetColorKey(tempBMP.GetPixel(0, 0), tempBMP.GetPixel(0, 0));
// Draw the image to your output using the transparancy key attributes
Bitmap outputImage = new Bitmap(this.Width,this.Height);
g = Graphics.FromImage(outputImage);
Rectangle destRect = new Rectangle(0, 0, tempBMP.Width, tempBMP.Height);
g.DrawImage(tempBMP, destRect, 0, 0, tempBMP.Width, tempBMP.Height,GraphicsUnit.Pixel, attr);
g.Dispose();
tempBMP.Dispose();
this.BackgroundImage = outputImage;
}
epaulsen
2009-04-02 09:12:13