在 PHP 中创建特定尺寸的图像并用黑色填充填充任何空间

问题描述 投票:0回答:1

想要在不裁剪的情况下调整图像大小以设置 (1080x1350) 的尺寸,只需用黑色边框/缓冲区填充死角即可。

由于我们无法控制用户上传图像的尺寸和长宽比。我希望创建一个 php 函数来创建一个尺寸设置为 1080x1350 的“画布”。

然后,我将用户图像放置在这个“画布”的中间(不裁剪),并用黑板填充任何死角。

这是我迄今为止所开发的:

// orignal image size
$width = imageSX($image);
$height = imageSY($image);


// canvas size
$thumb_width = 1080;
$thumb_height = 1350;


$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
        
if ( $original_aspect >= $thumb_aspect ) {
    $new_height = $thumb_height;
    $new_width = $width / ($height / $thumb_height);
} else {
    $new_width = $thumb_width;
    $new_height = $height / ($width / $thumb_width);
}
        
$tmp = imagecreatetruecolor( $thumb_width, $thumb_height );
imagealphablending($tmp, false);
imagesavealpha($tmp, true);
        
$transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127);
imagefilledrectangle($tmp, 0, 0, round($new_width), round($new_height), $transparent);
        
                
// Resize and crop
imagecopyresampled($tmp, $image, round(0 - ($new_width - $thumb_width) / 2), round(0 - ($new_height - $thumb_height) / 2), 0, 0, round($new_width), round($new_height), round($width), round($height));


我需要做出哪些改变才能达到预期的结果。我想我已经很接近了,但只是想提出一些想法。 谢谢你。

php image drawing gd
1个回答
0
投票

您可以将颜色更改为黑色而不是透明。让我们先用背景颜色填充整个画布,然后将图像放在中心。

试试这个代码,

// Original image size
$width = imagesx($image);
$height = imagesy($image);

// Canvas size
$thumb_width = 1080;
$thumb_height = 1350;

$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;

if ($original_aspect >= $thumb_aspect) {
    $new_height = $thumb_height;
    $new_width = $width / ($height / $thumb_height);
} else {
    $new_width = $thumb_width;
    $new_height = $height / ($width / $thumb_width);
}

$tmp = imagecreatetruecolor($thumb_width, $thumb_height);

// Set black background color for the canvas
$black = imagecolorallocate($tmp, 0, 0, 0);
imagefilledrectangle($tmp, 0, 0, $thumb_width, $thumb_height, $black);

// Disable alpha blending and enable saving alpha for PNG transparency support
imagealphablending($tmp, true);
imagesavealpha($tmp, true);

// Center the resized image on the canvas
$dst_x = round(($thumb_width - $new_width) / 2);
$dst_y = round(($thumb_height - $new_height) / 2);

imagecopyresampled($tmp, $image, $dst_x, $dst_y, 0, 0, round($new_width), round($new_height), $width, $height);

// Save the image or output (example: saving as a PNG)
imagepng($tmp, 'output_image.png');

// Cleanup
imagedestroy($tmp);
imagedestroy($image);
© www.soinside.com 2019 - 2024. All rights reserved.