Whenever I call PHP GD's imagecrop() on a PNG with transparency it is turning the transparent part black instead of maintaining it.
I have recently written a function to scale transparent PNGs whilst maintaining the transparency (see below), so I understand about using imagecopyresampled etc.
function scale_png($image, $resize_w = FALSE, $resize_h = FALSE, $alpha = 127)
{
$src_w = imagesx($image);
$src_h = imagesy($image);
if (! $resize_w) {$resize_w = $src_w;}
if (! $resize_h) {$resize_h = $src_h;}
$output = imagecreatetruecolor($resize_w, $resize_h);
imagealphablending($output, FALSE);
imagesavealpha($output, TRUE);
$transparent = imagecolorallocatealpha($output, 255, 255, 255, $alpha);
imagefilledrectangle($output, 0, 0, $resize_w, $resize_h, $transparent);
imagecopyresampled($output, $image, 0, 0, 0, 0, $resize_w, $resize_h, $src_w, $src_h);
return $output;
}
This function above is working fine, but when I also try to do imagecrop() on the same PNG this is when I get the black background.
Is there any easy way of performing this crop successfully? I can't seem to find any good examples.
I would rather not have to write another complex function like the one above in order to crop the image out using x, y, w, h and imagecopyresampled() if possible, as it's a major ball ache.
Any GD boffins out there care to impart their valued knowledge on me?
The way I understand there is nothing complicated here, you have to save the alpha channels before performing the crop.
$img = imagecreatefrompng("./cover.png");
imagealphablending($img, false);
imagesavealpha($img, true);
$resource = imagecrop($img, ['x' => 0, 'y' => 0, 'width' => 500, 'height' => 500]);