使用ImageMagick写入图像流数据时PHP卡住了

时间:2015-11-06 13:43:37

标签: php image cron imagemagick

我创建图片时有几天问题。

我有一个API,我将所有图像作为数组(RETS)。但是图像存储为二进制数据(不是文件URL,服务器中的某个位置)。但是也有一个损坏的图像数据,我无法检查它是否有效。我必须拉动所有数据(所有数据)在服务器中创建每个数组元素的图像。这就像是一项任务工作。但问题是,当我得到损坏的图像时,我的任务(php进程)卡住而且无法杀死它。

Rets图书馆:https://github.com/troydavisson/PHRETS

以下是我尝试使用ImageMagick的示例:

<?php

$path = '/var/www/assets/photo/test.jpg';
$image = new Imagick();

/** @var PHRETS\Models\Object $photo */

// from the $photo->getContent() i get the image binary data
if($image->readImageBlob($photo->getContent()) && $image->valid()) {
    // all photos looks like ok, but... when i try to run this command:
    $image->writeImage($path); // here php process is stuck if image is corrupted
}

当我说图像已损坏时,我的意思是,例如:

corrupted image (grey foreground at the bottom)

在底部有灰色前景,看起来没有写完或我得到坏图像。

我尝试做什么:

  1. 在StackOverflow的某个地方,我找到了从底部检查灰色的算法:

    function isGoodImage($fileData) {
        list($w, $h) = getimagesizefromstring($fileData);
    
        if ($w < MIN_WIDTH || $h < MIN_HEIGHT) return 0;
    
        $im = imagecreatefromstring($fileData);
        $grey = 0;
    
        for ($i = 0; $i < 5; ++$i) {
            for ($j = 0; $j < 5; ++$j) {
                $x = $w - 5 + $i;
                $y = $h - 5 + $j;
                list($r, $g, $b) = array_values(imagecolorsforindex($im, imagecolorat($im, $x, $y)));
                if ($r == $g && $g == $b && $b == 128)
                    ++$grey;
            }
        }
    
        return $grey < 12;
    }
    
  2. 另一种方法我只是尝试使用file_put_contents来保存文件,它的工作方式与ImageMagick相同,但也会影响不良图像。

  3. 我尝试将二进制数据转换为十六进制代码以检查\xFF\xD9的图像类型,并尝试捕获终结符(空字节)。但没有成功。

  4. 问题,当图像(作为二进制数据)坏(损坏)时如何捕获?因为我的任务不应该在cron运行时卡住。写作时ImageMagick不会返回异常,或者file_put_contents写入文件。

    此致,Donatas

0 个答案:

没有答案