简体   繁体   中英

Problem resizing PNG and placing it over larger transparent background in PHP/GD?

So, everything is working fine. I've got the Source PNG resizing and positioned correctly on the created background, but the other areas outside of the PNG turn black. I've gotten it to go transparent by using imagecolortransparent but this makes the png edges jaggy.

Here's what I have at the moment that's making black bars around the PNG. Keep in mind that I'm ONLY dealing with PNG images here.

// TARGET IMAGE
$target = imagecreatetruecolor($this->request['width'], $this->request['height']);
imagealphablending($target, false);
imagesavealpha($target, true);

// SOURCE IMAGE
$source = imagecreatefrompng($this->src_image);

// RESAMPLING
imagecopyresampled($target, $source, $offsetX, $offsetY, 0, 0, $tnWidth, $tnHeight, $this->src_width, $this->src_height);

// FINAL IMAGE
imagepng($target, $source, $quality);

// MEMORY CLEAN UP
imagedestroy($source);
imagedestroy($target);

// PRODUCES SOMETHING LIKE THIS

+--------------------------------+
|          BLACK AREA            |
+--------------------------------+
|                                |
|          RESIZED PNG           |
|       WITH TRANSPARENCY        |
|                                |
+--------------------------------+
|          BLACK AREA            |
+--------------------------------+


// WHERE IT SHOULD HAVE THE BLACK AREAS TRANSPARENT AS WELL

+--------------------------------+
|          TRANSPARENT           |
+--------------------------------+
|                                |
|          RESIZED PNG           |
|       WITH TRANSPARENCY        |
|                                |
+--------------------------------+
|          TRANSPARENT           |
+--------------------------------+

Hopefully someone has experience with this because all of the examples online that I've found only talk about resizing a PNG on a transparent BG the SAME size which is easy.

TIA

Ok, figured it out after many hours. So I hope this helps others.

// SOURCE PNG
$src    = imagecreatefrompng($this->src_image);

// DESTINATION CANVAS
$dst = imagecreatetruecolor($canvasW, $canvasH);
imagealphablending($dst, false);
$color = imagecolorallocatealpha($dst, 0, 0, 0, 127);
imagefill($dst, 0, 0, $color);
imagesavealpha($dst, true);

// RESAMPLE/RESIZE SOURCE AND TARGET TOGETHER
imagecopyresampled($dst, $src, $offsetX, $offsetY, 0, 0, $tnWidth, $tnHeight, $this->src_width, $this->src_height);

// WRITE FILE
imagepng($dst, $resized, $quality);

// MEMORY CLEAN UP
imagedestroy($src);
imagedestroy($dst);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM