phpthumbnailsphpthumb

How to generate image thumbnails in PHP in 300X200 dimensions?


I'm using the below code to generate image thumbnails in PHP. It generates the thumbnails proportional to the image height and width dimensions.

make_thumb('images/image.jpg', 'images-generated-thumbs/7.jpg', 300, 200);

function make_thumb($src, $dest, $desired_width, $desired_height) {

    /* read the source image */
    $source_image = imagecreatefromjpeg($src);
    $width = imagesx($source_image);
    $height = imagesy($source_image);

    /* find the "desired height" of this thumbnail, relative to the desired width  */
    $desired_height = floor($height*($desired_width/$width));
    $desired_width  = floor($width*($desired_height/$height));

    /* create a new, "virtual" image */
    $virtual_image = imagecreatetruecolor($desired_width, $desired_height);

    /* copy source image at a resized size */
    imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);

    /* create the physical thumbnail image to its destination */
    imagejpeg($virtual_image, $dest);
}

For the above example, it generates the 7.jpg thumbnail with 299x187 in size. So, my question is how to fill the rest of the pixels ((300-299)x(300-187)) in white color. If we remove the $desired_height variable in above code, it exactly generates a thumbnail with 300 in width, so only need is to fill the rest of the height with the white color.


Solution

  • Before you modify the width/height, store them:

    $actual_width = $desired_width;
    $actual_height = $desired_height;
    $desired_height = floor($height*($desired_width/$width));
    $desired_width  = floor($width*($desired_height/$height));
    

    When you are doing the canvas:

    /* create a new, "virtual" image */
    $virtual_image = imagecreatetruecolor($actual_width, $actual_height);
    

    Virtual image at this point is black, fill it with white:

    $white = imagecolorallocate($virtual_image, 255, 255, 255);
    imagefill($virtual_image, 0, 0, $white );