I have a script that uploads and resizes images using the GD library and PHP. I now want to upload a PNG image and for it to be stored as PNG and JPEG, I am then going to resize it but that's fine.
The problem I'm having is that sometimes, the converted version of the image (jpg) is distorted. Other times it is fine.
My code is taken from another answer here on StackOverflow:
function png2jpg($originalFile, $outputFile, $quality){
$image = imagecreatefrompng($originalFile);
imagejpeg($image, $outputFile, $quality);
imagedestroy($image);
}
An example of the distorted result is shown below, I am fully aware that I won't get the transparency on the JPG, I just want a white background. Any ideas?
I can't post images, so link to original: http://private.granvilleoil.com/prodImages/large/Petro-Patch.png) and JPG: http://private.granvilleoil.com/prodImages/large/Petro-Patch.jpg)
You need to create a fresh image with a white (or whatever you want) background and copy the none-transparent pixels from the png to that image:
function png2jpg($originalFile, $outputFile, $quality) {
$source = imagecreatefrompng($originalFile);
$image = imagecreatetruecolor(imagesx($source), imagesy($source));
$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);
imagecopy($image, $source, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, $outputFile, $quality);
imagedestroy($image);
imagedestroy($source);
}
PHP will only copy pixels from PNG files, and if your png has transparency this will not be handled by PHP resulting in what you see after conversion.
JPG format does not support transparent pixels.
Instead you can replace transparent pixels with white/black and then make the conversion:
function png2jpg($originalFile, $outputFile, $quality){
$size = getimagesize($originalFile);
$blank = imagecreate($size[0], $size[1]);
$newImage = imagecopymerge($blank, $originalFile, 0, 0, 0, 0, $size[0], $size[1], $quality);
png2jpg($newImage, $outputFile, );
$image = imagecreatefrompng($newImage);
imagejpeg($image, $outputFile, $quality);
}
Maybe if you try to make an image from png on top of a white image you could repair this problem.
There was a library I came across in http://www.phpclasses.org/ which is basically a wrapper over the GD library of PHP. It was called GDImageManipulation or something. Its a simple one file class, and it handles most of the preliminary image operations that you are talking about.
Take a look at it. It might help.