duanhuo3392 2016-03-17 15:34
浏览 101

如何在保持透明度的同时在PNG上使用PHP GD imagecrop?

Whenever I call PHP GD's imagecrop() on a PNG with transparency it is turning the transparent part black instead of maintaining it.

I have recently written a function to scale transparent PNGs whilst maintaining the transparency (see below), so I understand about using imagecopyresampled etc.

function scale_png($image, $resize_w = FALSE, $resize_h = FALSE, $alpha = 127)
{
    $src_w = imagesx($image);
    $src_h = imagesy($image);
    if (! $resize_w) {$resize_w = $src_w;}
    if (! $resize_h) {$resize_h = $src_h;}
    $output = imagecreatetruecolor($resize_w, $resize_h);
    imagealphablending($output, FALSE);
    imagesavealpha($output, TRUE);
    $transparent = imagecolorallocatealpha($output, 255, 255, 255, $alpha);
    imagefilledrectangle($output, 0, 0, $resize_w, $resize_h, $transparent);
    imagecopyresampled($output, $image, 0, 0, 0, 0, $resize_w, $resize_h, $src_w, $src_h);

    return $output;
}

This function above is working fine, but when I also try to do imagecrop() on the same PNG this is when I get the black background.

Is there any easy way of performing this crop successfully? I can't seem to find any good examples.

I would rather not have to write another complex function like the one above in order to crop the image out using x, y, w, h and imagecopyresampled() if possible, as it's a major ball ache.

Any GD boffins out there care to impart their valued knowledge on me?

  • 写回答

1条回答 默认 最新

  • dtpxi88884 2017-09-15 11:56
    关注

    The way I understand there is nothing complicated here, you have to save the alpha channels before performing the crop.

    $img = imagecreatefrompng("./cover.png");
    imagealphablending($img, false);
    imagesavealpha($img, true);
    $resource = imagecrop($img, ['x' => 0, 'y' => 0, 'width' => 500, 'height' => 500]);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100