When building a website, it is usually necessary to reduce the image to a suitable size. It is easier to reduce the jpg image. If the png image has a transparent color, if it is reduced according to the jpg method, the transparent color will be lost. So how to deal with it to preserve the transparent color?
Mainly use two methods of the gd library:
imagecolorallocatealpha assign color + alpha
imagesavealpha is set to save the complete alpha channel information when saving png images
- //Get the source image gd image identifier
- $srcImg = imagecreatefrompng('./src.png');
- $srcWidth = imagesx($srcImg );
- $srcHeight = imagesy($srcImg);
-
- //Create a new image
- $newWidth = round($srcWidth / 2);
- $newHeight = round($srcHeight / 2);
- $newImg = imagecreatetruecolor($ newWidth, $newHeight);
- //Assign color + alpha, fill the color onto the new image
- $alpha = imagecolorallocatealpha($newImg, 0, 0, 0, 127);
- imagefill($newImg, 0, 0, $ alpha);
-
- //Copy the source image to the new image, and set it to save the complete alpha channel information when saving the PNG image
- imagecopyresampled($newImg, $srcImg, 0, 0, 0, 0, $newWidth, $ newHeight, $srcWidth, $srcHeight);
- imagesavealpha($newImg, true);
- imagepng($newImg, './dst.png');
Copy code
|