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

透明背景的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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效