PHP: 需要将 imagemagick 命令转换为 php 脚本

PHP: Need to convert imagemagick command to php script

我用这个命令来批量修改网站的图片。它们必须是这个尺寸才能适合主题。

现在我也想在 Facebook 广告中使用这些图片,但必须调整它们的大小。我使用的命令(工作正常)是:

for i in `ls -1 *.jpg`; do convert $i -fuzz 10% -trim +repage -resize 980x1200 -background white -gravity center -extent 980x1200 $i; done

现在我需要制作一个 PHP 脚本来执行相同的操作,但还要 return 将图像作为响应。

我得出以下结论:

<?php

/* Create the object and read the image in */
$im = new Imagick("image.jpg");

/* Trim the image with 10% fuzz */
$im->trimImage(10);

/* Repage */
$im->setImagePage(0, 0, 0, 0);

/* Resize */
$im->resizeImage(1200,628,Imagick::FILTER_LANCZOS,0);

/* Add Borders*/
$im->setImageBackgroundColor('White');
$im->setGravity('Centre');
$im->setImageExtent(1200,628);

/* Output the image */
header("Content-Type: image/" . $im->getImageFormat());
echo $im;
?>

不幸的是,它似乎不起作用。它所做的只是 return 一个黑色矩形(看起来像脚本中使用的正确尺寸)。

我在 运行 此代码时遇到的第一个错误:

PHP Warning: Imagick::setgravity() expects parameter 1 to be integer, string given in resize.php on line 18

请尝试使用 imagick::GRAVITY_CENTER

下一期,Imagick::resizeImage()Imagick::setImageExtent() 期望参数按宽度、高度顺序排列。

最后,尝试为 Imagick::resizeImage() 上的模糊设置一个非零值,例如 1,以解决黑色图像问题。

我不确定你是如何尝试获得边框的,但你可能想看看 Imagick::borderImage()

我不知道这是否能解决你所有的问题,但它应该会让你更接近!

<?php

/* Create the object and read the image in */
$im = new Imagick("image.jpg");

/* Trim the image with 10% fuzz */
$im->trimImage(10);

/* Repage */
$im->setImagePage(0, 0, 0, 0);

/* Resize */
$im->resizeImage(628, 1200, Imagick::FILTER_LANCZOS, 1);

/* Add Borders*/
$im->setImageBackgroundColor('White');
$im->setGravity(Imagick::GRAVITY_CENTER);
$im->setImageExtent(628, 1200);

/* Output the image */
header("Content-Type: image/" . $im->getImageFormat());
echo $im;
?>

您可以使用“shell_exec(您的命令)”在 php 中执行 运行 命令。尝试一次这可能对你有用。 参考 http://php.net/manual/en/function.shell-exec.php