问题
I use this command to batch modify images for a site. They need to be this size to suit the theme.
Now I also want to use these images in Facebook Ads, but they have to be resized. The command I use (which works fine) is:
for i in `ls -1 *.jpg`; do convert $i -fuzz 10% -trim +repage -resize 980x1200 -background white -gravity center -extent 980x1200 $i; done
Now I need to make a PHP script that does the same, but also returns the image as response.
I came up with the following:
<?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;
?>
Unfortunately it doesn't seem to work. All it does is return a black rectangle (which looks like the right dimensions as used in the script).
回答1:
First error I get when running this code:
PHP Warning: Imagick::setgravity() expects parameter 1 to be integer, string given in resize.php on line 18
Try using imagick::GRAVITY_CENTER
instead.
Next issue, Imagick::resizeImage()
and Imagick::setImageExtent()
expect parameters in width, height order.
Finally, try setting a non-zero value like 1 for blur on Imagick::resizeImage()
to resolve the black image issue.
I'm not sure how you are trying to get a border, but you may want to look at Imagick::borderImage()
.
I don't know if that will solve all your problems, but it should get you a lot closer!
<?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;
?>
回答2:
you can run commands in php using " shell_exec(your command) ". Try once this may works for you. Refer http://php.net/manual/en/function.shell-exec.php
来源:https://stackoverflow.com/questions/43129275/php-need-to-convert-imagemagick-command-to-php-script