png圖片如果帶了透明色按照jpg的方式來縮小,就會造成透明色損失。那么如何處理才能保存透明色呢?下面的代碼就可以解決這個問題.
主要是利用gd庫的兩個方法:
- imagecolorallocatealpha //分配顏色 + alpha
- imagesavealpha //設置在保存 png 圖像時保存完整的 alpha 通道信息
代碼示例:
- //獲取源圖gd圖像標識符
- $srcImg = imagecreatefrompng('./src.png');
- $srcWidth = imagesx($srcImg);
- $srcHeight = imagesy($srcImg);
- //創建新圖
- $newWidth = round($srcWidth / 2);
- $newHeight = round($srcHeight / 2);
- $newImg = imagecreatetruecolor($newWidth, $newHeight);
- //分配顏色 + alpha,將顏色填充到新圖上
- $alpha = imagecolorallocatealpha($newImg, 0, 0, 0, 127);
- imagefill($newImg, 0, 0, $alpha);
- //Vevb.com
- //將源圖拷貝到新圖上,并設置在保存 PNG 圖像時保存完整的 alpha 通道信息
- imagecopyresampled($newImg, $srcImg, 0, 0, 0, 0, $newWidth, $newHeight, $srcWidth, $srcHeight);
- imagesavealpha($newImg, true);
- imagepng($newImg, './dst.png');
新聞熱點
疑難解答