Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create image with transparent background using GDI+?

Tags:

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 ?

like image 309
Julien Poulin Avatar asked Apr 02 '09 08:04

Julien Poulin


People also ask

How do I give an image a transparent background?

You can create a transparent area in most pictures. Select the picture that you want to create transparent areas in. Click Picture Tools > Recolor > Set Transparent Color. In the picture, click the color you want to make transparent.


1 Answers

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.

like image 80
OregonGhost Avatar answered Sep 22 '22 20:09

OregonGhost