如何在300X200尺寸的PHP中生成图像缩略图?

时间:2014-03-13 16:35:16

标签: php thumbnails phpthumb

我正在使用以下代码在PHP中生成图像缩略图。它会生成与图像高度和宽度尺寸成比例的缩略图。

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

对于上面的示例,它会生成大小为299x187的7.jpg缩略图。所以,我的问题是如何填充白色的其余像素((300-299)x(300-187))。 如果我们删除上面代码中的$desired_height变量,它会生成一个宽度为300的缩略图,因此只需要用白色填充其余高度。

1 个答案:

答案 0 :(得分:2)

在修改宽度/高度之前,请存储它们:

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

当你在做画布时:

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

此时的虚拟图像为黑色,用白色填充:

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