James Holland
James Holland

Reputation: 161

PHP PNG to JPG conversion issue, image distorted

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)

Upvotes: 0

Views: 4017

Answers (4)

Niko
Niko

Reputation: 26730

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);
}

Upvotes: 2

Caner
Caner

Reputation: 59198

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);
}

Upvotes: 0

Spidfire
Spidfire

Reputation: 5533

Maybe if you try to make an image from png on top of a white image you could repair this problem.

Upvotes: 0

slash197
slash197

Reputation: 9034

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.

Upvotes: 0

Related Questions