Cheekysoft Cheekysoft - 1 year ago 42
PHP Question

How do I resize and convert an uploaded image to a PNG using GD

I want to allow users to upload avatar-type images in a variety of formats (GIF, JPEG, and PNG at least), but to save them all as PNG database BLOBs. If the images are oversized, pixelwise, I want to resize them before DB-insertion.

What is the best way to use GD to do the resizing and PNG conversion?

Edit: Sadly, only GD is available on the server I need to use, no ImageMagick.

Answer Source
Resizes an image and converts it to PNG returning the PNG data as a string
function imageToPng($srcFile, $maxSize = 100) {  
    list($width_orig, $height_orig, $type) = getimagesize($srcFile);        

    // Get the aspect ratio
    $ratio_orig = $width_orig / $height_orig;

    $width  = $maxSize; 
    $height = $maxSize;

    // resize to height (orig is portrait) 
    if ($ratio_orig < 1) {
        $width = $height * $ratio_orig;
    // resize to width (orig is landscape)
    else {
        $height = $width / $ratio_orig;

    // Temporarily increase the memory limit to allow for larger images
    ini_set('memory_limit', '32M'); 

    switch ($type) 
        case IMAGETYPE_GIF: 
            $image = imagecreatefromgif($srcFile); 
        case IMAGETYPE_JPEG:  
            $image = imagecreatefromjpeg($srcFile); 
        case IMAGETYPE_PNG:  
            $image = imagecreatefrompng($srcFile);
            throw new Exception('Unrecognized image type ' . $type);

    // create a new blank image
    $newImage = imagecreatetruecolor($width, $height);

    // Copy the old image to the new image
    imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

    // Output to a temp file
    $destFile = tempnam();
    imagepng($newImage, $destFile);  

    // Free memory                           

    if ( is_file($destFile) ) {
        $f = fopen($destFile, 'rb');   
        $data = fread($f);       

        // Remove the tempfile
        return $data;

    throw new Exception('Image conversion failed.');