[php] Use PHP to convert PNG to JPG with compression?

I have a bunch of high quality PNG files. I want to use PHP to convert them to JPG because of it's smaller file sizes while maintaining quality. I want to display the JPG files on the web.

Does PHP have functions/libraries to do this? Is the quality/compression any good?

This question is related to php png jpeg

The answer is


Be careful of what you want to convert. JPG doesn't support alpha-transparency while PNG does. You will lose that information.

To convert, you may use the following function:

// Quality is a number between 0 (best compression) and 100 (best quality)
function png2jpg($originalFile, $outputFile, $quality) {
    $image = imagecreatefrompng($originalFile);
    imagejpeg($image, $outputFile, $quality);
    imagedestroy($image);
}

This function uses the imagecreatefrompng() and the imagejpeg() functions from the GD library.


<?php
function createThumbnail($imageDirectory, $imageName, $thumbDirectory, $thumbWidth) {
    $explode = explode(".", $imageName);
    $filetype = $explode[1];

    if ($filetype == 'jpg') {
        $srcImg = imagecreatefromjpeg("$imageDirectory/$imageName");
    } else
    if ($filetype == 'jpeg') {
        $srcImg = imagecreatefromjpeg("$imageDirectory/$imageName");
    } else
    if ($filetype == 'png') {
        $srcImg = imagecreatefrompng("$imageDirectory/$imageName");
    } else
    if ($filetype == 'gif') {
        $srcImg = imagecreatefromgif("$imageDirectory/$imageName");
    }

    $origWidth = imagesx($srcImg);
    $origHeight = imagesy($srcImg);

    $ratio = $origWidth / $thumbWidth;
    $thumbHeight = $origHeight / $ratio;

    $thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
    imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $origWidth, $origHeight);

    if ($filetype == 'jpg') {
        imagejpeg($thumbImg, "$thumbDirectory/$imageName");
    } else
    if ($filetype == 'jpeg') {
        imagejpeg($thumbImg, "$thumbDirectory/$imageName");
    } else
    if ($filetype == 'png') {
        imagepng($thumbImg, "$thumbDirectory/$imageName");
    } else
    if ($filetype == 'gif') {
        imagegif($thumbImg, "$thumbDirectory/$imageName");
    }
}
    ?>

This is a very good thumbnail script =) Here's an example:

$path = The path to the folder where the original picture is. $name = The filename of the file you want to make a thumbnail of. $thumbpath = The path to the directory where you want the thumbnail to be saved into. $maxwidth = the maximum width of the thumbnail in PX eg. 100 (wich will be 100px).

createThumbnail($path, $name, $thumbpath, $maxwidth);


I know it's not an exact answer to the OP, but as answers have already be given...

Do you really need to do this in PHP ?
What I mean is : if you need to convert a lot of images, doing it in PHP might not be the best way : you'll be confronted to memory_limit, max_execution_time, ...

I would also say GD might not get you the best quality/size ratio ; but not sure about that (if you do a comparison between GD and other solutions, I am very interested by the results ;-) )

Another approach, not using PHP, would be to use Image Magick via the command line (and not as a PHP extension like other people suggested)

You'd have to write a shell-script that goes through all .png files, and gives them to either

  • convert to create a new .jpg file for each .png file
  • or mogrify to directly work on the original file and override it.


As a sidenote : if you are doing this directly on your production server, you could put some sleep time between bunches of conversions, to let it cool down a bit sometimes ^^


I've use the shell script + convert/mogrify a few times (having them run for something like 10 hours one time), and they do the job really well :-)


You might want to look into Image Magick, usually considered the de facto standard library for image processing. Does require an extra php module to be installed though, not sure if any/which are available in a default installation.

HTH.


This is a small example that will convert 'image.png' to 'image.jpg' at 70% image quality:

<?php
$image = imagecreatefrompng('image.png');
imagejpeg($image, 'image.jpg', 70);
imagedestroy($image);
?>

Hope that helps


See this list of php image libraries. Basically it's GD or Imagemagick.


PHP has some image processing functions along with the imagecreatefrompng and imagejpeg function. The first will create an internal representation of a PNG image file while the second is used to save that representation as JPEG image file.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to png

Convert UIImage to NSData and convert back to UIImage in Swift? Importing PNG files into Numpy? What is difference between png8 and png24 How to change the background colour's opacity in CSS Darkening an image with CSS (In any shape) Android splash screen image sizes to fit all devices How to convert a SVG to a PNG with ImageMagick? Convert RGBA PNG to RGB with PIL Set transparent background using ImageMagick and commandline prompt Converting a byte array to PNG/JPG

Examples related to jpeg

Image steganography that could survive jpeg compression How do I insert a JPEG image into a python Tkinter window? JPG vs. JPEG image formats C# Base64 String to JPEG Image Changing all files' extensions in a folder with one command on Windows Convert RGBA PNG to RGB with PIL Converting a byte array to PNG/JPG Python Image Library fails with message "decoder JPEG not available" - PIL matplotlib savefig in jpeg format Accessing JPEG EXIF rotation data in JavaScript on the client side