Resize images with transparency in php

2019-02-12 12:31发布

I have looked all over for how to correctly manage alpha when I'm resizing a png. I've managed to get it to keep transparency, but only for pixels that are completely transparent. Here's my code:

$src_image = imagecreatefrompng($file_dir.$this->file_name);
$dst_image = imagecreatetruecolor($this->new_image_width, $this->new_image_height);
imagealphablending($dst_image, true);
imagesavealpha($dst_image, true);
$black = imagecolorallocate($dst_image, 0, 0, 0);
imagecolortransparent($dst_image, $black);
imagecopyresampled($dst_image, $src_image, 0, 0, 0, 0, $this->new_image_width, 
                 $this->new_image_height, $this->image_width, $this->image_height);
imagepng($dst_image, $file_dir.$this->file_name);

Starting with this source image:

enter image description here

The resized image looks like this:

enter image description here

The solution for almost every forum post I've looked at about this issue say to do something like this:

imagealphablending($dst_image, false);
$transparent = imagecolorallocatealpha($dst_image, 0, 0, 0, 127);
imagefill($dst_image, 0, 0, $transparent);

The results from this code fails at saving any alpha whatsoever:

enter image description here

Is there any other solution? Am I missing something with the alpha blending? Why would that work for everyone else, yet utterly fail for me? I'm using MAMP 2.1.3 and PHP 5.3.15.

2条回答
爷的心禁止访问
2楼-- · 2019-02-12 13:07
"They have not worked at all and I'm not sure why."

Well you must have been doing something wrong. The code from the linked duplicate with a couple of lines added to load and save the image:

$im = imagecreatefrompng(PATH_TO_ROOT."var/tmp/7Nsft.png");

$srcWidth = imagesx($im);
$srcHeight = imagesy($im);

$nWidth = intval($srcWidth / 4);
$nHeight = intval($srcHeight /4);

$newImg = imagecreatetruecolor($nWidth, $nHeight);
imagealphablending($newImg, false);
imagesavealpha($newImg,true);
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight,
    $srcWidth, $srcHeight);

imagepng($newImg, PATH_TO_ROOT."var/tmp/newTest.png");

Produces the image:

A resized PNG with transparency

i.e. this question (and answer) are a complete duplicate.

查看更多
We Are One
3楼-- · 2019-02-12 13:09

i have used simpleImage class for resizing image. You can re-size your image with maintaining aspect ratio. this class is using imagecreatetruecolor and imagecopyresampled core Php functions to re-size image

  $new_image = imagecreatetruecolor($width, $height);
  imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
  $this->image = $new_image;

find complete code at http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/

查看更多
登录 后发表回答