具有透明背景的图像裁剪变为黑色

时间:2018-08-21 13:05:45

标签: php image ubuntu

我在从base64string裁剪图像时遇到问题,它在我的本地主机上运行良好,但是当我将其上传到远程服务器时,透明背景为黑色。

$base64String = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAlongbase64string...."
//see: https://pastebin.com/zqVumGPi for the full base64string

$contentType = explode(':', substr($base64String, 0, strpos($base64String, ';')))[1];

$dataIn = str_replace("data:{$contentType};base64,", '', $base64String);
$dataIn = str_replace(' ', '+', $dataIn);
$dataIn = base64_decode($dataIn);
$src = imagecreatefromstring($dataIn);

$width = 960;
$height = 640;

$dst = imagecreatetruecolor($width, $height);

// Create transparency
imagesavealpha($dst, true);
$color = imagecolorallocatealpha($dst, 0, 0, 0, 127);
imagefill($dst, 0, 0, $color);

imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $width, $height);

$to_crop_array = array('x' =>intval(187) , 'y' => intval(48), 'width' => 320, 'height'=> 320);

//This is where the transparency disappears on my server. 
//It works fine on localhost
$thumb_im = imagecrop($dst, $to_crop_array);

header('Content-Type: image/png');
imagepng($thumb_im);

根据phpInfo,我在本地主机和远程服务器上使用的是PHP版本7.2.1。我在使用的是PHP版本7.2.7-0ubuntu0.18.04.2

本地主机上的GD版本是2.1.0,而在删除服务器上是2.2.5。

本地主机上的LibPNG版本是1.6.27,而在我的远程服务器上,它正在使用1.6.34。 我的服务器在Ubuntu 18.04.1 LTS上运行,由DigitalOcean托管。 我已经在另一台与LibPng和Php具有相同版本的服务器上尝试了此代码,并且运行良好。

1 个答案:

答案 0 :(得分:0)

我已经改用Imagick解决了。

这是我的解决方案,如果将来有人会偶然发现这个问题

$contentType = explode(':', substr($base64String, 0, strpos($base64String, ';')))[1];

// Decode base64
$dataIn = str_replace("data:{$contentType};base64,", '', $base64String);
$dataIn = str_replace(' ', '+', $dataIn);
$imageBlob = base64_decode($dataIn);

$imagick = new Imagick();
$imagick->readImageBlob($imageBlob);
$imagick->cropImage(400,400, 30,10);

header('Content-Type: image/'.$imagick->getImageFormat());
echo $imagick->getImageBlob();
相关问题