將圖片縮成合適的尺寸,jpg圖片縮小比較容易,png圖片如果帶了透明色,按jpg方式來縮小,會造成透明色丟失。
保存透明色主要利用gd庫的兩個方法:
imagecolorallocatealpha 分配顏色 + alpha
imagesavealpha 設置在保存png圖像時保存完整的 alpha 通道信息
代碼如下:
//獲取源圖gd圖像標識符
$srcImg = imagecreatefrompng('./source.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);
//將源圖拷貝到新圖上,並設置在保存 PNG 圖像時保存完整的 alpha 通道信息
imagecopyresampled($newImg, $srcImg, 0, 0, 0, 0, $newWidth, $newHeight, $srcWidth, $srcHeight);
imagesavealpha($newImg, true);
imagepng($newImg, './thumb.png');
查看本欄目