如何在PHP中透明地调整png的大小?

Rya*_*rty 40 php png gd resize

我试图在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);
Run Code Online (Sandbox Code Playgroud)


更新 "不工作"我的意思是当我调整pngs时,背景颜色会变为黑色.

Dyc*_*cey 77

据我所知,您需要执行imagecolorallocatealpha()之前将混合模式设置为false,并将保存alpha通道标志设置为true

<?php
 $newImg = imagecreatetruecolor($nWidth, $nHeight);
 imagealphablending($newImg, false);
 imagesavealpha($newImg,true);
 $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
 imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
 imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight,
                      $imgInfo[0], $imgInfo[1]);
?>
Run Code Online (Sandbox Code Playgroud)

更新:此代码仅适用于透明度不透明度= 0的背景.如果您的图像具有0 <不透明度<100,则它将是黑色背景.

  • 这对我来说不起作用,仍然是黑色背景. (3认同)

小智 10

这是一个适合我的最终解决方案.

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;
}
Run Code Online (Sandbox Code Playgroud)


hki*_*ame 6

与 imagecopyresampled 相比,使用 imagescale 更好。调整大小的图像不需要空图像资源,与 imagecopyresampled 所需的十个参数相比,仅需要两个参数。还可以以更小的尺寸生产更好的质量。如果使用 PHP 5.5.18 或更早版本,或者 PHP 5.6.2 或更早版本,您应该提供第三个参数的高度,因为长宽比计算不正确。

$this->image =   imagecreatefrompng($filename);
$scaled = imagescale($this->image, $width);
imagealphablending($scaled, false);
imagesavealpha($scaled, true);
imagepng($scaled, $filename);
Run Code Online (Sandbox Code Playgroud)