【问题标题】:PHP Image Resize and Expand Placeholder (Transparent)PHP 图像调整大小和展开占位符(透明)
【发布时间】:2019-06-07 20:04:40
【问题描述】:

我正在尝试缩小垂直透明 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);

【问题讨论】:

    标签: php image-processing gd


    【解决方案1】:

    最后让它工作:

    • 使用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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      • 2013-06-03
      • 1970-01-01
      • 2010-09-07
      • 1970-01-01
      • 1970-01-01
      • 2011-03-29
      相关资源
      最近更新 更多