将PHP/GD包装器移植到Imagick的问题

Ali*_*xel 15 php gd image imagemagick imagick

我最近发现,与GD相比,Imagick可以支持颜色配置文件,从而产生质量更好的图像(有关更多详细信息,请参阅此问题/答案),所以我试图将我的GD包装器移植到使用Imagick类,而不是目前的GD实现如下:

function Image($input, $crop = null, $scale = null, $merge = null, $output = null, $sharp = true)
{
    if (isset($input, $output) === true)
    {
        if (is_string($input) === true)
        {
            $input = @ImageCreateFromString(@file_get_contents($input));
        }

        if (is_resource($input) === true)
        {
            $size = array(ImageSX($input), ImageSY($input));
            $crop = array_values(array_filter(explode('/', $crop), 'is_numeric'));
            $scale = array_values(array_filter(explode('*', $scale), 'is_numeric'));

            if (count($crop) == 2)
            {
                $crop = array($size[0] / $size[1], $crop[0] / $crop[1]);

                if ($crop[0] > $crop[1])
                {
                    $size[0] = round($size[1] * $crop[1]);
                }

                else if ($crop[0] < $crop[1])
                {
                    $size[1] = round($size[0] / $crop[1]);
                }

                $crop = array(ImageSX($input) - $size[0], ImageSY($input) - $size[1]);
            }

            else
            {
                $crop = array(0, 0);
            }

            if (count($scale) >= 1)
            {
                if (empty($scale[0]) === true)
                {
                    $scale[0] = round($scale[1] * $size[0] / $size[1]);
                }

                else if (empty($scale[1]) === true)
                {
                    $scale[1] = round($scale[0] * $size[1] / $size[0]);
                }
            }

            else
            {
                $scale = array($size[0], $size[1]);
            }

            $image = ImageCreateTrueColor($scale[0], $scale[1]);

            if (is_resource($image) === true)
            {
                ImageFill($image, 0, 0, IMG_COLOR_TRANSPARENT);
                ImageSaveAlpha($image, true);
                ImageAlphaBlending($image, true);

                if (ImageCopyResampled($image, $input, 0, 0, round($crop[0] / 2), round($crop[1] / 2), $scale[0], $scale[1], $size[0], $size[1]) === true)
                {
                    $result = false;

                    if ((empty($sharp) !== true) && (is_array($matrix = array_fill(0, 9, -1)) === true))
                    {
                        array_splice($matrix, 4, 1, (is_int($sharp) === true) ? $sharp : 16);

                        if (function_exists('ImageConvolution') === true)
                        {
                            ImageConvolution($image, array_chunk($matrix, 3), array_sum($matrix), 0);
                        }
                    }

                    if ((isset($merge) === true) && (is_resource($merge = @ImageCreateFromString(@file_get_contents($merge))) === true))
                    {
                        ImageCopy($image, $merge, round(0.95 * $scale[0] - ImageSX($merge)), round(0.95 * $scale[1] - ImageSY($merge)), 0, 0, ImageSX($merge), ImageSY($merge));
                    }

                    foreach (array('gif' => 0, 'png' => 9, 'jpe?g' => 90) as $key => $value)
                    {
                        if (preg_match('~' . $key . '$~i', $output) > 0)
                        {
                            $type = str_replace('?', '', $key);
                            $output = preg_replace('~^[.]?' . $key . '$~i', '', $output);

                            if (empty($output) === true)
                            {
                                header('Content-Type: image/' . $type);
                            }

                            $result = call_user_func_array('Image' . $type, array($image, $output, $value));
                        }
                    }

                    return (empty($output) === true) ? $result : self::Chmod($output);
                }
            }
        }
    }

    else if (count($result = @GetImageSize($input)) >= 2)
    {
        return array_map('intval', array_slice($result, 0, 2));
    }

    return false;
}
Run Code Online (Sandbox Code Playgroud)

我一直在尝试使用Imagick类方法,这是我到目前为止所得到的:

function Imagick($input, $crop = null, $scale = null, $merge = null, $output = null, $sharp = true)
{
    if (isset($input, $output) === true)
    {
        if (is_file($input) === true)
        {
            $input = new Imagick($input);
        }

        if (is_object($input) === true)
        {
            $size = array_values($input->getImageGeometry());
            $crop = array_values(array_filter(explode('/', $crop), 'is_numeric'));
            $scale = array_values(array_filter(explode('*', $scale), 'is_numeric'));

            if (count($crop) == 2)
            {
                $crop = array($size[0] / $size[1], $crop[0] / $crop[1]);

                if ($crop[0] > $crop[1])
                {
                    $size[0] = round($size[1] * $crop[1]);
                }

                else if ($crop[0] < $crop[1])
                {
                    $size[1] = round($size[0] / $crop[1]);
                }

                $crop = array($input->getImageWidth() - $size[0], $input->getImageHeight() - $size[1]);
            }

            else
            {
                $crop = array(0, 0);
            }

            if (count($scale) >= 1)
            {
                if (empty($scale[0]) === true)
                {
                    $scale[0] = round($scale[1] * $size[0] / $size[1]);
                }

                else if (empty($scale[1]) === true)
                {
                    $scale[1] = round($scale[0] * $size[1] / $size[0]);
                }
            }

            else
            {
                $scale = array($size[0], $size[1]);
            }

            $image = new IMagick();
            $image->newImage($scale[0], $scale[1], new ImagickPixel('white'));

            $input->cropImage($size[0], $size[1], round($crop[0] / 2), round($crop[1] / 2));
            $input->resizeImage($scale[0], $scale[1], Imagick::FILTER_LANCZOS, 1); // $image->scaleImage($scale[0], $scale[1]);

            //if (in_array('icc', $image->getImageProfiles('*', false)) === true)
            {
                $version = preg_replace('~([^-]*).*~', '$1', ph()->Value($image->getVersion(), 'versionString'));

                if (is_file($profile = sprintf('/usr/share/%s/config/sRGB.icm', str_replace(' ', '-', $version))) !== true)
                {
                    $profile = 'http://www.color.org/sRGB_v4_ICC_preference.icc';
                }

                if ($input->profileImage('icc', file_get_contents($profile)) === true)
                {
                    $input->setImageColorSpace(Imagick::COLORSPACE_SRGB);
                }
            }

            $image->compositeImage($input, Imagick::COMPOSITE_OVER, 0, 0);

            if ((isset($merge) === true) && (is_object($merge = new Imagick($merge)) === true))
            {
                $image->compositeImage($merge, Imagick::COMPOSITE_OVER, round(0.95 * $scale[0] - $merge->getImageWidth()), round(0.95 * $scale[1] - $merge->getImageHeight()));
            }

            foreach (array('gif' => 0, 'png' => 9, 'jpe?g' => 90) as $key => $value)
            {
                if (preg_match('~' . $key . '$~i', $output) > 0)
                {
                    $type = str_replace('?', '', $key);
                    $output = preg_replace('~^[.]?' . $key . '$~i', '', $output);

                    if (empty($output) === true)
                    {
                        header('Content-Type: image/' . $type);
                    }

                    $image->setImageFormat($type);

                    if (strcmp('jpeg', $type) === 0)
                    {
                        $image->setImageCompression(Imagick::COMPRESSION_JPEG);
                        $image->setImageCompressionQuality($value);
                        $image->stripImage();
                    }

                    if (strlen($output) > 0)
                    {
                        $image->writeImage($output);
                    }

                    else
                    {
                        echo $image->getImageBlob();
                    }
                }
            }

            return (empty($output) === true) ? $result : self::Chmod($output);
        }
    }

    else if (count($result = @GetImageSize($input)) >= 2)
    {
        return array_map('intval', array_slice($result, 0, 2));
    }

    return false;
}
Run Code Online (Sandbox Code Playgroud)

已经支持基本功能(裁剪/调整大小/水印),但是,我仍然遇到一些问题.由于PHP Imagick文档有点糟糕,除了尝试所有可用方法和参数的试错方法组合之外别无选择,这需要花费大量时间.

我目前的问题/疑虑是:


1 - 保持透明度

在我原来的实现中,行:

ImageFill($image, 0, 0, IMG_COLOR_TRANSPARENT);
ImageSaveAlpha($image, true);
ImageAlphaBlending($image, true);
Run Code Online (Sandbox Code Playgroud)

将透明PNG图像转换为PNG输出时,具有保持透明度的效果.但是,如果尝试将透明PNG图像转换为JPEG格式,则透明像素的颜色应设置为白色.到目前为止,使用ImageMagick,我只能将所有透明像素转换为白色,但如果输出格式支持透明像素,则无法保留透明度.


2 - 压缩输出格式(即JPEG和PNG)

我的原始实现在PNG上使用9的压缩级别,在JPEG上使用90的质量:

foreach (array('gif' => 0, 'png' => 9, 'jpe?g' => 90) as $key => $value)
Run Code Online (Sandbox Code Playgroud)

线条:

$image->setImageCompression(Imagick::COMPRESSION_JPEG);
$image->setImageCompressionQuality($value);
$image->stripImage();
Run Code Online (Sandbox Code Playgroud)

似乎压缩JPEG图像 - 然而,GD能够使用与$value质量参数相同的方式压缩它- 为什么?关于以下两者之间的差异,我也处于黑暗中:

我应该使用哪一个,它们的区别是什么?此外,最关键的问题与PNG压缩有关,Imagick压缩常量列表似乎不支持PNG格式:

imagick::COMPRESSION_UNDEFINED (integer)
imagick::COMPRESSION_NO (integer)
imagick::COMPRESSION_BZIP (integer)
imagick::COMPRESSION_FAX (integer)
imagick::COMPRESSION_GROUP4 (integer)
imagick::COMPRESSION_JPEG (integer)
imagick::COMPRESSION_JPEG2000 (integer)
imagick::COMPRESSION_LOSSLESSJPEG (integer)
imagick::COMPRESSION_LZW (integer)
imagick::COMPRESSION_RLE (integer)
imagick::COMPRESSION_ZIP (integer)
imagick::COMPRESSION_DXT1 (integer)
imagick::COMPRESSION_DXT3 (integer)
imagick::COMPRESSION_DXT5 (integer)
Run Code Online (Sandbox Code Playgroud)

这是一个屁股画,因为如果用Imagick输出(大小约为2 MB),GD PNG输出恰好大小为100-200 KB会变得非常胖...

一对夫妇 的问题 上SO 关于这个问题,但我一直没能找到不依赖于外部应用程序的任何工作的解决方案.这对ImageMagick来说真的不可能吗?!


3 - 图像卷积

在GD实现中,我调用ImageConvolution()了锐化图像,我知道Imagick有内置的方法来锐化图像(我还没有机会尝试它们)但是我想知道Imagick是否有相当于ImageConvolution()功能.


4 - 颜色配置文件

这与原始实现无关,但我也想做对.

我是否应该始终将Imagick/International Color Consortium sRGB颜色配置文件添加到所有图像中?或者只有在有(或没有)特定颜色配置文件时才添加?

另外,我应该删除现有的颜色配置文件吗?

我理解这可能是一个广泛的问题,但我对颜色配置文件的理解非常有限,对此的一些一般性指导将非常感激.


5 - 打开远程图像

GD本身支持经由开口远程图像,必须ImageCreateFrom*的功能,或使用file_get_contents()结合ImageCreateFromString()等我做.

Imagick似乎只能打开本地图像或打开文件句柄.是否有任何直接的方法使Imagick读取远程图像(无需打开和关闭文件句柄)?


如果有人能够对这些问题有所了解,我将非常感激.

提前致谢!

toc*_*777 13

您的PNG图像可能会增加大小的原因有很多,您将遇到的最明显的原因是GM/IM无法传达作为tRNS块的透明度(基本上是PNG图像的布尔透明度).不幸的是,GraphicsMagick和ImageMagick的维护者尚未实现此功能.我和他们交换了电子邮件,所以我肯定知道这一点.

我知道你不想使用外部工具但是相信我.Image/GraphicsMagick在压缩PNG图像方面非常糟糕.我使用的解决方案是,使用GraphicsMagick来操作图像,并检查图像是否包含透明像素,如果它包含透明像素,则在图像上运行OptiPNG.OptiPNG将看到透明度可以作为tRNS块传达并相应地采取行动.实际上你应该在使用Image/GraphicsMagick之后在所有PNG图像上运行OptiPNG,因为我发现你可以实现更大的压缩.您还可以通过关闭抖动和使用YUV颜色空间来节省空间.

至于GM比IM更好地减小图像的大小,你应该知道GM默认使用8位色彩空间,而色彩还原图像,而ImageMagick默认使用16位.这就是为什么当颜色将图像颜色减少到超过255种颜色时,GM比IM快得多.也许您应该在压缩后检查每个图像中的颜色数量以确认.