0

我正在使用以下代码在 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);
}

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

4

1 回答 1

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 );
于 2014-03-13T18:36:51.017 回答