在PHP/GD中调整PNG大小并将其置于更大的透明背景上的问题


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

所以,一切都很好。我已经调整了源PNG的大小,并正确地定位在创建的背景上,但PNG以外的其他区域变成黑色。我已经通过imagecolortransparent让它变得透明,但这会使png边缘锯齿状。

这是我现在在PNG周围制作的黑条。请记住,我这里只处理PNG图像。

// 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           |
+--------------------------------+

希望有人有这方面的经验,因为我在网上找到的所有例子都是关于在透明BG上调整PNG大小的,这很容易。

TIA

好吧,花了好几个小时才弄明白。所以我希望这对别人有帮助。

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