使用PHP和Imagick

时间:2019-06-07 12:23:27

标签: php imagemagick imagick

我有一些使用PHP和Imagick(ImageMagick)编写的脚本来修剪背景图像,填充纯色并调整大小,但是我需要根据图像内容翻转图像。

所有图像的所有内容都必须在左侧,然后我需要分析图像并检测大部分内容在右侧还是左侧,如果在右侧检测到内容,则需要翻转(我有翻转代码)图片)。

例如:

有效图片。图像的大部分部分/线条/内容在左侧。

Valid Image

无效的图像。图像的大部分部分/线条/内容在右边,必须翻转。

enter image description here

有什么方法可以检测到这一点?

谢谢!

1 个答案:

答案 0 :(得分:0)

我的最终脚本:

<?php
/**
 * @param string $image
 * @param string $side
 *
 * @return \Imagick
 */
function flop(string $image, string $side): Imagick
{
    $image = new Imagick($image);

    $clone = clone($image);
    $clone->resizeImage(200, 200, Imagick::FILTER_CATROM, 1, true);
    $clone->modulateImage(100, 0, 100);

    $w = $clone->getImageWidth();
    $h = $clone->getImageHeight();

    $wHalf = $w / 2;
    $right = $left = 0;

    for ($x = 0; $x < $w; ++$x) {
        for ($y = 0; $y < $h; ++$y) {
            if ($clone->getImagePixelColor($x, $y)->getColorAsString() === 'srgb(255,255,255)') {
                continue;
            }

            if ($x > $wHalf) {
                ++$right;
            } else {
                ++$left;
            }
        }
    }

    if (($side === 'left') && ($right > $left)) {
        $image->flopImage();
    } elseif (($side === 'right') && ($left > $right)) {
        $image->flopImage();
    }

    return $image;
}
相关问题