Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does WebImage.Resize strip out PNG transparency

Using WebImage from the MVC3/WebMatrix release. Loading the following image from a file path:

Sample Image - or - enter image description here

Running the following code against it:

return new WebImage(path)
       .Resize(120, 265)
       .GetBytes("Png");

Results in an image with the transparency stripped out and black used in place:

Blacked out transparency

The same happens with RotateRight(), RotateLeft() and FlipHorizantal() However if I don't call the .Resize() method:

return new WebImage(path)
        .GetBytes("Png");

The image is returned without an issue.

like image 200
Richard Slater Avatar asked Feb 15 '11 16:02

Richard Slater


1 Answers

Is your image 8-bit (indexed color)? When 8-bit images are resized, they are often converted from indexed color to RGB in order to make the result look smoother. Resizing images without changing the color table rarely ends well.

If the image is already RGB (24-bit or more), it's a little more complex: What should the resizer do for the edges of an image, on the border between "transparent" and "not transparent"? Many resizing algorithms will do something resembling "averaging the two colors" at a border (again, to make the image look smoother), but most have no concept of transparency, let alone PNG's ability to have multiple levels of translucency.

So, the short answer is "it's probably a bug" -- not a full implementation of PNG's features.

The solution may not exist, but I'd try:

  1. Stay in 8-bit color if that is an option, or convert ahead of time to 32-bit.
  2. Get the color, or color index, of the transparent color. After resizing, force that value to be transparent. Note that due to the aforementioned "smoothing", the edges between transparent and non-transparent may not be that color, and will probably look like some blend of black and whatever color you actually want.
  3. If nothing else, you may need to use an external library which gives you more control.
like image 192
Charles Burns Avatar answered Nov 16 '22 00:11

Charles Burns