我试图在PHP中调整透明背景的png,我在网上找到的代码示例对我不起作用.这是我正在使用的代码,建议将不胜感激!
$this->image = imagecreatefrompng($filename); imagesavealpha($this->image, true); $newImage = imagecreatetruecolor($width, $height); // Make a new transparent image and turn off alpha blending to keep the alpha channel $background = imagecolorallocatealpha($newImage, 255, 255, 255, 127); imagecolortransparent($newImage, $background); imagealphablending($newImage, false); imagesavealpha($newImage, true); imagecopyresampled($newImage, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); $this->image = $newImage; imagepng($this->image,$filename);
更新
"不工作"我的意思是当我调整pngs时,背景颜色会变为黑色.
据我所知,您需要在执行imagecolorallocatealpha()之前将混合模式设置为false
,并将保存alpha通道标志设置为true
更新:此代码仅适用于透明度不透明度= 0的背景.如果您的图像具有0 <不透明度<100,则它将是黑色背景.
这是一个适合我的最终解决方案.
function resizePng($im, $dst_width, $dst_height) { $width = imagesx($im); $height = imagesy($im); $newImg = imagecreatetruecolor($dst_width, $dst_height); imagealphablending($newImg, false); imagesavealpha($newImg, true); $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127); imagefilledrectangle($newImg, 0, 0, $width, $height, $transparent); imagecopyresampled($newImg, $im, 0, 0, 0, 0, $dst_width, $dst_height, $width, $height); return $newImg; }