php reduction png image without loss of transparent color solution
- 2020-12-09 00:46:27
- OfStack
There are mainly two ways to use the gd library:
imagecolorallocatealpha // Distribution of color + alpha
imagesavealpha // Set in save png When the image is saved intact alpha The channel information
Code examples:
// Access to the source diagram gd Image identifier
$srcImg = imagecreatefrompng('./src.png');
$srcWidth = imagesx($srcImg);
$srcHeight = imagesy($srcImg);
// Create a new
$newWidth = round($srcWidth / 2);
$newHeight = round($srcHeight / 2);
$newImg = imagecreatetruecolor($newWidth, $newHeight);
// Distribution of color + alpha , fill the new drawing with color
$alpha = imagecolorallocatealpha($newImg, 0, 0, 0, 127);
imagefill($newImg, 0, 0, $alpha);
// Copy the source diagram to the new diagram and set it to save PNG When the image is saved intact alpha The channel information
imagecopyresampled($newImg, $srcImg, 0, 0, 0, 0, $newWidth, $newHeight, $srcWidth, $srcHeight);
imagesavealpha($newImg, true);
imagepng($newImg, './dst.png');