调整大小的图像与背景填充垂直和水平的图像

问题描述 投票:5回答:1

我想创建一个图片库。我想试试这一次与PHP难懂的。

当一个文件被上传我希望它被调整到1024x724。如果图像是垂直的(宽度<高度)我希望它在图像和透明背景的中心被装配(或白色如果不可能)在两侧,其中应该是空白的,因此图像可以是始终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);
php imagemagick
1个回答
12
投票

如果我理解你想要正确的东西,你已经有一部分的方式。现在,如果你尝试使用一个透明的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作为测试transparent1.png和$thumbnailFilename作为测试transparent1.sized.png,测试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);

==每个评论更新:==

对于那些谁得出这个答案,6.5.7-8后使用ImageMagick,这个答案需要进行调整,以使extentImage x和y的值都为负。你可以在php.net/manual/en/imagick.extentimage.php看到警告说明 - 杰夫·理查兹的礼貌

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.