【问题标题】:How to enlarge an image with it's border colors如何用它的边框颜色放大图像
【发布时间】:2022-08-05 19:01:44
【问题描述】:

我正在缩放图像以在网站上使用,但需要固定大小和纵横比。 Imagick() 可以调整大小,但我找不到用边框像素填充额外空间的方法,如以下问题:https://legacy.imagemagick.org/discourse-server/viewtopic.php?t=34525。我在这里查看了所有示例:https://phpimagick.com/Imagick,但它们不是我需要的。
有谁知道使用 Imagick() 类从 PHP 执行此操作的方法?
提前致谢!

由于“非重点问题”而更新:我需要一个解决方案来使用 PHP 中的 Imagick() 类来做到这一点:

我有以下代码来调整图像大小:

$im = new Imagick(\'myImage.png\');
$im->resizeImage(900, 400, Imagick::FILTER_CATCOM, 0.9, true);
$im->extentImage(1600, 400, -350, 0);

此代码将原始图像的大小(例如 450 x 200 像素)调整为 900 x 400 像素,然后将其扩展到 1600 x 400 像素,将调整大小的图像置于中间。这按预期工作,但不使用图像的边框像素来扩展图像。

使用第一条评论中提到的 $im->distort() 应该是解决方案,但我不知道在哪里放置它以及使用什么参数。

  • 看到该线程中的答案使用了distort 命令,我打赌PHP 版本将使用distort() 函数。

标签: php imagick


【解决方案1】:

不理想(不是很快),但它比我想要的做得更好。

$sImg = 'path/to/my/image'; /* 435 x 609 pixels in my example */
$iWidth = 880; /* width of the final image */
$iHeight = 584; /* height of the final image */
$nWidth = 417;  /* width of the scaled image */
$nHeight = 584; /* height of the scaled image */

# Open and resize the original image
$im = new Imagick($cfgClient[$client]['path']['frontend'] . $sImg);
$im->setImageOpacity(1.0);
$im->resizeImage($nWidth, $nHeight, Imagick::FILTER_CATROM, 0.9, true);

# Create a new image with the desired sizes
$im2 = new Imagick();
$im2->newImage($iWidth, $iHeight, 'none');
$im2->setImageFormat('png');
$im2->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);
$im2->setImageOpacity(1.0);

# Copy the image scaled down from every corner
$im1 = new Imagick($sImg);
$im1->setImageOpacity(1.0);
if (($iWidth - $nWidth) > ($iHeight - $nHeight)) {
    $fFactor = (($iHeight == $nHeight) ? 0 : ((($iWidth - $nWidth) / 2) / (($iHeight - $nHeight) / 2)));
    for ($i = 0, $n = (($iWidth - $nWidth) / 2); $i <= $n; $i += 2) {
        $im1->adaptiveResizeImage(($iWidth - ($i * 2)), ($iHeight - ($i * $fFactor * 2)));
        $im2->compositeImage($im1, Imagick::COMPOSITE_DEFAULT, $i, ($i * $fFactor));
    }
}
else {
    $fFactor = (($iWidth == $nWidth) ? 0 : ((($iHeight - $nHeight) / 2) / (($iWidth - $nWidth) / 2)));
    for ($i = 0, $n = (($iHeight - $nHeight) / 2); $i <= $n; $i += 2) {
        $im1->adaptiveResizeImage(($iWidth - ($i * $fFactor * 2)), ($iHeight - ($i * 2)));
        $im2->compositeImage($im1, Imagick::COMPOSITE_DEFAULT, ($i * $fFactor), $i);
    }
}
$im2->blurImage(1, 1);

# Copy the scaled image over the extended image
$im2->compositeImage($im, Imagick::COMPOSITE_DEFAULT, (($iWidth - $nWidth) / 2), (($iHeight - $nHeight) / 2));

# Save the image
$im2->writeImage('path/to/new/file');

# Cleanup
unset($im, $im1, $im2);

这创造了

如果有人能找到更快的解决方案,请在此处发布。
谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    相关资源
    最近更新 更多