Home > Backend Development > PHP Tutorial > PHP code to maintain transparency when scaling png images

PHP code to maintain transparency when scaling png images

WBOY
Release: 2016-07-25 08:43:53
Original
1020 people have browsed it
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
  1. //Get the source image gd image identifier
  2. $srcImg = imagecreatefrompng('./src.png');
  3. $srcWidth = imagesx($srcImg );
  4. $srcHeight = imagesy($srcImg);
  5. //Create a new image
  6. $newWidth = round($srcWidth / 2);
  7. $newHeight = round($srcHeight / 2);
  8. $newImg = imagecreatetruecolor($ newWidth, $newHeight);
  9. //Assign color + alpha, fill the color onto the new image
  10. $alpha = imagecolorallocatealpha($newImg, 0, 0, 0, 127);
  11. imagefill($newImg, 0, 0, $ alpha);
  12. //Copy the source image to the new image, and set it to save the complete alpha channel information when saving the PNG image
  13. imagecopyresampled($newImg, $srcImg, 0, 0, 0, 0, $newWidth, $ newHeight, $srcWidth, $srcHeight);
  14. imagesavealpha($newImg, true);
  15. imagepng($newImg, './dst.png');
Copy code

php, png


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template