dtn43447
2018-08-21 13:05
浏览 181
已采纳

透明背景的Imagecrop变黑

I am having a problem with cropping a image from a base64string, it works perfectly fine on my localhost but when I upload it to my remote server the transparent background is black.

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

According to phpInfo I am using PHP Version 7.2.1 on my localhost and on my remote server I am using PHP Version 7.2.7-0ubuntu0.18.04.2

GD Version on localhost is 2.1.0 and on the remove server it is 2.2.5.

LibPNG Version on localhost is 1.6.27 and on my remote server it is using 1.6.34. My server runs on Ubuntu 18.04.1 LTS and it is hosted by DigitalOcean. I have tried this code on another server with the same versions on LibPng and Php and it worked fine.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doumeba0486 2018-08-22 15:32
    已采纳

    I have solved it by using Imagick instead.

    Here is my solution if someone might stumble upon this problem in the future

    $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();
    
    打赏 评论

相关推荐 更多相似问题