PHP 图片调整大小和扩展占位符(透明)

PHP Image Resize and Expand Placeholder (Transparent)

我正在尝试缩小垂直透明 png 图像的大小,并使占位符为正方形(透明背景)。

结果,我得到了透明的图像,但占位符的左右两边都是黑色的(黑色-透明-黑色)。请帮助让占位符的所有区域透明,谢谢。

$info = getimagesize($source);
$imgtype = image_type_to_mime_type($info[2]);

switch ($imgtype) {
    case 'image/jpeg':
        $src_image = imagecreatefromjpeg($source);
        break;
    case 'image/gif':
        $src_image = imagecreatefromgif($source);
        break;
    case 'image/png':
        $src_image = imagecreatefrompng($source);
        break;
    default:
        die('Invalid image type.');
}

$new_w = 300;
$new_h = 300;

$src_x = 0;
$src_y = 0;
$src_w = imagesx($src_image);
$src_h = imagesy($src_image);

$dst_h = round($new_h);
$dst_w = round(($dst_h / $src_h) * $src_w);
$dst_y = 0;
$dst_x = ($new_w - $dst_w) / 2;

$dst_image = imagecreatetruecolor($new_w, $new_h);
$alphacolor = imagecolorallocate($dst_image, 255, 255, 255);
imagecolortransparent($dst_image, $alphacolor);

imagealphablending($dst_image, false);
imagesavealpha($dst_image, true);

imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);

imagepng($dst_image, $destination, 0);

终于让它工作了:

  • 使用 imagecolorallocatealpha 代替 imagecolorallocate
  • 使用 imagefilledrectangle 代替 imagecolortransparent
  • 在执行 imagecolorallocate() 之前将混合模式设置为 false,并将 alpha 通道标志保存为 true。

工作代码:

$info = getimagesize($source);
$imgtype = image_type_to_mime_type($info[2]);

switch ($imgtype) {
    case 'image/jpeg':
        $src_image = imagecreatefromjpeg($source);
        break;
    case 'image/gif':
        $src_image = imagecreatefromgif($source);
        break;
    case 'image/png':
        $src_image = imagecreatefrompng($source);
        break;
    default:
        die('Invalid image type.');
}

$src_x = 0;
$src_y = 0;
$src_w = imagesx($src_image);
$src_h = imagesy($src_image);

$dst_h = round($new_h);
$dst_w = round(($dst_h / $src_h) * $src_w);
$dst_y = 0;
$dst_x = ($new_w - $dst_w) / 2;

$dst_image = imagecreatetruecolor($new_w, $new_h);

imagealphablending($dst_image, false);
imagesavealpha($dst_image, true);

$alphacolor = imagecolorallocatealpha($dst_image, 255, 255, 255, 127);
imagefilledrectangle($dst_image, 0, 0, $new_w, $new_h, $alphacolor);

imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);

imagepng($dst_image, $destination, 0);