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

时间:2019-01-13 17:15:40

标签: php image-processing gd

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

Sample Image

结果是,我得到透明图像,但占位符的左侧和右侧为黑色(black-transparent-black)。请帮助使占位符的所有区域保持透明,谢谢。

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

1 个答案:

答案 0 :(得分:0)

最后通过以下方法使它起作用:

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

工作代码

imagecolortransparent