【问题标题】:Resize image with background fill for vertical and horizontal images使用垂直和水平图像的背景填充调整图像大小
【发布时间】:2013-02-17 01:20:17
【问题描述】:

我正在尝试创建一个图片库。这次我想试试 PHP Image Magick。

上传文件后,我希望将其大小调整为 1024x724。如果图像是垂直的(宽度

如果图像是水平的(宽度 > 高度),同样适用。

到目前为止,这是我的代码:

$img = new Imagick($targetFile);
$img->scaleImage(1024,724);
$img->setGravity(imagick::GRAVITY_CENTER);
$img->setImageBackgroundColor('white');
$img->extentImage(1024,724,0,0);

$img->writeImage($targetFile);

$img = new Imagick($targetFile);
$img->scaleImage(150,150);
$img->setGravity(imagick::GRAVITY_CENTER);
$img->setImageBackgroundColor('white');
$img->extentImage(150,150,0,0);

$img->writeImage($targetThumb);

【问题讨论】:

  • 不确定命令行参数的其余部分,但如果您想要 Web 可见的透明度,则必须使用 .png 或 .gif。 Jpeg 格式不支持透明度。

标签: php imagemagick


【解决方案1】:

如果我正确理解了您想要的内容,那么您已经完成了一部分。现在,如果您尝试使用透明的 PNG(源和目标)而不是 jpeg,它将使图像变平并使背景变为纯白色,您不希望这样吗?

您需要做的是确定图像是否具有或可能具有透明度,然后将背景颜色设置为无。 -extent 使图像变平,因此在这些情况下,为了保持透明度,背景需要为 None。 (而且,如上所述,您当然需要使用 png 或 gif 输出而不是 jpg,因为 jpeg 无法处理透明度。)通常我会进行简单的扩展检查,因为它在大多数情况下已经足够好了,but there are more detailed checks.

$background = preg_match('/\.gif$|\.png$/', $thumbnailFilename) == 1 ? 'None' : 'white';
$edge = shell_exec("convert $imgFile -resize 1024x724 -background $background -gravity center -extent 1024x724 -quality 90 $thumbnailFilename");

我在这里检查输出缩略图,因为如果您要输出到 jpeg,无论来源如何,它都会被剥夺透明度。有了这个,如果你提供 $imgFile 作为 test-transparent1.png 和 $thumbnailFilename 作为 test-transparent1.sized.png,test-transparent1.sized.png 的大小应该适合 1024x724 并用透明像素填充,所以原始图像居中。

==为 ImageMagick PHP 类编辑:==

首先,为了进行比例缩放,您需要将 scaleImage 的最佳拟合参数设置为 true。此外,当您使用 API 时,extentImage 似乎根本不使用重力选项,因此我们必须使用负 X 或 Y 偏移来将图像正确居中在新画布上。这是我的测试脚本运行后的样子:

<?php
$targetFile = 'mizu.png';
$targetThumb = 'mizu.thumb.png';

$background = preg_match('/\.gif$|\.png$/', $targetThumb) == 1 ? 'None' : 'white';

$img = new Imagick($targetFile);

$img->scaleImage(150,150,true);
$img->setImageBackgroundColor($background);
$w = $img->getImageWidth();
$h = $img->getImageHeight();
$img->extentImage(150,150,($w-150)/2,($h-150)/2);
$img->writeImage($targetThumb);

== 每个 cmets 更新:==

对于那些在6.5.7-8之后使用imagemagick的人,需要调整这个答案,使extentImage的x和y值为负。您可以在 php.net/manual/en/imagick.extentimage.php 看到警告说明 - 由 Jeff Richards 提供

【讨论】:

  • 还有一件事。这可以用 php 类完成吗?我的意思是像 $img = new Imagick('test.jpg');和 $img = resize to 2014x 724 像这样?如果你理解我
  • 是的,Imagick 类应该可以做到这一点。特别是,请查看 scaleImagesetImageBackgroundColorsetGravityextentImage 方法的手动条目。
  • 好的 我编辑了我的帖子,它重新调整了图像的大小,但没有保留纵横比。你能帮我解决我的问题吗?
  • 我对 Imagick 课程不是很熟悉,所以我推迟了回复您的时间。对于那个很抱歉。无论如何,希望我刚刚编辑到我的答案中的示例代码会有所帮助。
  • 好吧,我们快到了,只是重力s...t。它总是使图像为 150x150,但图像位于左侧,即使我输入 $img->setGravity(imagick::GRAVITY_CENTER);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-19
相关资源
最近更新 更多