Transparent PNG To JPG Conversion
Categories: Uncategorized
Converting a semi-transparent PNG to a JPG without severe artifacts or “transparent area color meshing” is a much harder task than you would expect. I thought it would be as simple as loading the image into Image_Transform and using _generate(null, 'jpg')
to convert the image to a jpeg. Well, that code will convert it to a jpeg, but all the areas that are semi-transparent end up looking absolutely horrible becoming sort of flattened. The solution is to use the wonderful Image Magick image processing library to draw the image onto a background color of your choice:
[code lang=”php”]
header(“Content-Type: image/jpeg”);
list($width, $height) = getimagesize($pic);
//the below function should be passthru, but for some reason WP would not let me write that in…
passthr(“convert -size “.escapeshellarg($width.”x”.$height).” -draw ‘image Over 0,0 0,0 “.realpath($pic).”‘ xc:white jpg:-“);[/code]
The above PHP script successfully converts a semi-transparent PNG to a jpeg with a white background (obviously, you need to have passthru() enabled for this script to work). You can change the background color by changing the xc:white
part of the shell script to whatever color suites your needs (xc:gray
, for example). The original shell script was taken from here.
As an aside, learning to use the Image Magick command line tools isn’t an easy task. The command syntax is very unorthodox and it very confusing. I found the following resources very useful while trying to learn the Image Magick CLI: