【问题标题】:Resize images with transparency in php在php中使用透明度调整图像大小
【发布时间】:2013-06-03 09:24:18
【问题描述】:

在调整 png 大小时,我已全面了解如何正确管理 alpha。我设法让它保持透明度,但仅限于完全透明的像素。这是我的代码:

$src_image = imagecreatefrompng($file_dir.$this->file_name);
$dst_image = imagecreatetruecolor($this->new_image_width, $this->new_image_height);
imagealphablending($dst_image, true);
imagesavealpha($dst_image, true);
$black = imagecolorallocate($dst_image, 0, 0, 0);
imagecolortransparent($dst_image, $black);
imagecopyresampled($dst_image, $src_image, 0, 0, 0, 0, $this->new_image_width, 
                 $this->new_image_height, $this->image_width, $this->image_height);
imagepng($dst_image, $file_dir.$this->file_name);

从这个源图像开始:

调整大小后的图像如下所示:

我看过的关于这个问题的几乎所有论坛帖子的解决方案都说要做这样的事情:

imagealphablending($dst_image, false);
$transparent = imagecolorallocatealpha($dst_image, 0, 0, 0, 127);
imagefill($dst_image, 0, 0, $transparent);

此代码的结果无法保存任何 alpha:

还有其他解决办法吗?我错过了阿尔法混合的东西吗?为什么这对其他人有用,而对我却完全失败?我正在使用 MAMP 2.1.3 和 PHP 5.3.15。

【问题讨论】:

标签: php resize png gd alpha


【解决方案1】:
"They have not worked at all and I'm not sure why."

你一定是做错了什么。链接副本中的代码添加了几行以加载和保存图像:

$im = imagecreatefrompng(PATH_TO_ROOT."var/tmp/7Nsft.png");

$srcWidth = imagesx($im);
$srcHeight = imagesy($im);

$nWidth = intval($srcWidth / 4);
$nHeight = intval($srcHeight /4);

$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,
    $srcWidth, $srcHeight);

imagepng($newImg, PATH_TO_ROOT."var/tmp/newTest.png");

生成图像:

即这个问题(和答案)完全重复。

【讨论】:

  • 你们都有什么平台,PHP / GD / Imagemagick 的版本?这大概就是原因。或者,堆栈溢出可能会重新处理源图像,因此您不会测试相同的图像。
【解决方案2】:

我使用 simpleImage 类来调整图像大小。 您可以在保持纵横比的情况下重新调整图像大小。 此类使用 imagecreatetruecolorimagecopyresampled 核心 Php 函数来调整图像大小

  $new_image = imagecreatetruecolor($width, $height);
  imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
  $this->image = $new_image;

http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/找到完整代码

【讨论】:

  • 这不是一个问题,但它是题外话,因为 asker 专门针对 PHP 的内置 GD 库......(这应该是评论,而不是回答)
猜你喜欢
  • 1970-01-01
  • 2010-09-07
  • 1970-01-01
  • 2014-04-14
  • 2011-08-04
  • 1970-01-01
  • 1970-01-01
  • 2012-09-15
  • 2011-03-29
相关资源
最近更新 更多