Persits Software, Inc. Knowledge Base Articles

Thumbnails of PNG images contain unexpected background patterns

Problem Description

When creating the thumbnail of a PNG image with AspJpeg, the background of the thumbnail sometimes contains an unsightly pattern (usually stripe-like) as shown on the images below:

Original PNG Image:

JPEG thumbnail produced by AspJpeg:


If the thumbnail contains an unexpected background pattern, it means the original PNG image contains it also but it is invisible. For it to be invisible on the thumbnail as well, the thumbnail must be saved in PNG format instead of JPEG.

Some PNG images contain an "alpha channel" that makes some areas of the image fully or partially transparent. A fully transparent area is effectively invisible when viewed by a standard image viewer.

The alpha channel is a feature only found in PNG format. When AspJpeg creates a thumbnail, it creates it in JPEG format by default and therefore the alpha channel is lost. The transparent areas which were previously invisible are now exposed. (It is unclear why those stripe-like patterns are put in PNG images in the first place but they are apparently quite common.)

AspJpeg Versions prior to 2.7

To preserve the alpha channel in the thumbnail, take advantage of AspJpeg's PNG output functionality by setting the property PNGOutput to True when resizing a PNG image. For example:

Set Jpeg = Server.CreateObject("Persits.Jpeg")
Jpeg.Open( Path )

' ... set new width and height

If Jpeg.OriginalFormat = "PNG" Then
  Jpeg.PNGOutput = True
  Jpeg.Save "c:\path\thumb.png"
  Jpeg.Save "c:\path\thumb.jpg"
End If

AspJpeg 2.7+

As of Version 2.7, you can take advantage of the method FlattenAlpha which applies the alpha channel to the image's pixels in combination with the specified background color and then removes the alpha channel, thus effectively "flattening" the image:

This enables you to save the thumbnail in JPEG format regardless of whether the original image has an alpha channel:

Set Jpeg = Server.CreateObject("Persits.Jpeg")
Jpeg.Open( Path )

Jpeg.FlattenAlpha &HFFFFFFFF ' White background

' ... set new width and height

Jpeg.Save "c:\path\thumb.jpg"

For more information about AspJpeg's PNG output and alpha channel management functions, see Chapter 10 of the AspJpeg user manual.