Creating an alpha transparency mask in ASP using csImageFile

The csImageFile component has the functionality to import an alpha transparency channel to an image. In this example, two instances of the component are used. One loads a photograph and resizes it while the other creates an alpha mask of an ellipse. The result of combining the two is a photograph that appears elliptical in shape when it is displayed in a web browser.

ASP produced alpha transparency mask

Frame

First the code to create the alpha mask. The NewImage command creates a new image that is black. A white ellipse is drawn onto this image. When imported as an alpha channel, black pixels are fully opaque and white are fully transparent. The settings for BrushColor and BrushStyle make the ellipse filled with white. The Antialias property makes the edge of the ellipse smooth.

Set Alpha = Server.CreateObject("csImageFile.Manage")
Alpha.NewImage 360, 270, "000000"
Alpha.PenColor = "FFFFFF"
Alpha.BrushColor = "FFFFFF"
Alpha.BrushStyle = 0
Alpha.Antialias = true
Alpha.Ellipse 50, 50, 310, 220

ASP code to mask the outside of an image

Photograph

The photograph used here needs to be resized. It is essential that the alpha mask and the photograph are the same size.

Set Image = Server.CreateObject("csImageFile.Manage")
Image.ReadFile "c:\images\photo.jpg"
Image.ResizeFit 360, 270

ASP code to mask an elliptical area around an image

Final Image

Finally, the alpha mask is imported to the photograph and the resulting image is streamed to the browser. The alpha mask image is converted to 8 bit greyscale automatically so there is no need to call the GrayScale method. If it is not the exact same dimensions as the photograph it will generate an error.

The use of Antialias makes the edge of the ellipse partially transparent so it blends into the background.

Image.AlphaHDC = Alpha.BMPHandle
Response.ContentType = "image/png"
Response.BinaryWrite Image.PNGData

It is also possible to load an alpha mask from a bitmap file using the LoadAlphaAsBMP method.

Support for alpha transparency has been introduced in version 6.2 of csImageFile and it is limited to PNG images. Additional functionality was added for version 6.4.7 to be able to extract, add or edit an alpha channel. We have another example using alpha transparency where two images are merged but the background image contains an alpha channel that must be applied to the combined image.