Imagick Resize,Center和Sparse Fill问题

时间:2012-09-08 01:53:59

标签: php resize imagemagick center imagick

我的最终目标是将输入图像的大小调整为100px宽度,125px高度。一些输入图像是不同的宽高比,所以我希望它们在一个100x125的容器中,背景稀疏的边缘颜色填充。

好的,所以这适用于基本调整大小:

$image = new Imagick($imgFile);
$image->resizeImage(100,0, Imagick::FILTER_LANCZOS, 1, false);
$image->writeImage("$Dir/$game.png");
header("Content-type: ".$image->getImageFormat());
echo $image;
$image->clear();
$image->destroy();

但是我一直在寻找几个小时,而且我找不到一个简单的“这就是你在画布中居中图像的位置”,用于PHP的Imagick库。一切都是为了实际的ImageMagick转换应用程序,这不是我真正想要的。我已经尝试将已调整大小的图像合成为具有设置宽度和高度的空newImage,但它似乎只是覆盖尺寸而不管复合类型,将Gravity设置为居中,然后将范围设置为100x125无效(总是如此)坐在0,0,并尝试将y偏移设置为((125-imageheight)/ 2)导致偏移量超出应有的程度)

编辑:

    $imageOutput = new Imagick();
    $image = new Imagick($imgFile);
    $image->resizeImage(100,0, Imagick::FILTER_LANCZOS, 1, false);
    $imageOutput->newImage(100, 125, new ImagickPixel('black'));
    $imageOutput->compositeImage($image, Imagick::COMPOSITE_ADD, 0, ((125 - $image->getImageHeight()))/2 );
    $imageOutput->setImageFormat('png');
    $imageOutput->writeImage("$Dir/$game.png");
    header("Content-type: ".$imageOutput->getImageFormat());
    echo $imageOutput;
    $image->clear();
    $image->destroy();

所以我的中心工作,重力显然对实际图像没有影响。

我完全不知道在哪里开始尝试使用库在PHP中重新创建命令行边缘稀疏填充。

1 个答案:

答案 0 :(得分:2)

我最终使用了Imagick和shell调用的组合来转换自己,我最终会重写它以完全使用shell调用。我也改变了我的尺寸,这是代码:

    $imageOutput = new Imagick(); // This will hold the resized image
    $image = new Imagick($imgFile); // Open image file
    $image->resizeImage(120,0, Imagick::FILTER_LANCZOS, 1, false); // Resize it width-wise
    $imageOutput->newImage(120, 150, "none"); // Make the container with transparency
    $imageOutput->compositeImage($image, Imagick::COMPOSITE_ADD, 0, ((150 - $image->getImageHeight())/2) ); // Center the resized image inside of the container
    $imageOutput->setImageFormat('png'); // Set the format to maintain transparency
    $imageOutput->writeImage("$Dir/$game.temp.png"); // Write it to disk
    $image->clear(); //cleanup -v
    $image->destroy(); 
    $imageOutput->clear();
    $imageOutput->destroy();
    //Now the real fun
    $edge = shell_exec("convert $Dir/$game.temp.png -channel A -morphology EdgeIn Diamond $Dir/$game.temp.edge.png"); // Get the edges of the box, create an image from just that
    $shepards = shell_exec("convert $Dir/$game.temp.edge.png txt:- | sed '1d; / 0) /d; s/:.* /,/;'"); // get the pixel coordinates
    $final = shell_exec("convert $Dir/$game.temp.edge.png -alpha off -sparse-color shepards '$shepards' png:- | convert png:- $Dir/$game.temp.png -quality 90 -composite $Dir/$game.jpg"); // Sparse fill the entire container using the edge of the other image as shepards , then composite that on top of this new image
    unlink("$Dir/$game.temp.png"); // cleanup temp files
    unlink("$Dir/$game.temp.edge.png");
    set_header_and_serve("$Dir/$game.jpg"); // serve the newly created file