1

我正在处理大量图像。我必须为每个图像创建四个 JPEG 版本:

  • 原始尺寸 JPEG
  • 700x430 版本
  • 57x57 缩略图
  • 167xN 缩略图(可变高度,保持纵横比)

我使用了以下两个辅助函数:

function thumbFixed($srcfile, $dstfile, $dstWidth, $dstHeight) {
    $srcImg = imagecreatefromstring(file_get_contents($srcfile));
    list($srcWidth, $srcHeight) = getimagesize($srcfile);
    $srcAR = $srcWidth / $srcHeight;

    $dstAR = $dstWidth / $dstHeight;

    $dstImg = imagecreatetruecolor($dstWidth, $dstHeight);

    if($srcAR >= $dstAR) {
        $cropHeight = $dstHeight;
        $cropWidth = (int)($dstHeight * $srcAR);
    } else {
        $cropWidth = $dstWidth;
        $cropHeight = (int)($dstWidth / $srcAR);
    }

    $cropImg = imagecreatetruecolor($cropWidth, $cropHeight);
    imagecopyresampled($cropImg, $srcImg, 0, 0, 0, 0, $cropWidth, $cropHeight, $srcWidth, $srcHeight);

    $dstOffX = (int)(($cropWidth - $dstWidth) / 2);
    $dstOffY = (int)(($cropHeight - $dstHeight) / 2);

    imagecopy($dstImg, $cropImg, 0, 0, $dstOffX, $dstOffY, $dstWidth, $dstHeight);
    imagejpeg($dstImg, $dstfile);
}

function thumbGrid($srcfile, $dstfile, $dstWidth) {
    $srcImg = imagecreatefromstring(file_get_contents($srcfile));
    list($srcWidth, $srcHeight) = getimagesize($srcfile);
    $srcAR = $srcWidth / $srcHeight;

    $dstHeight = $dstWidth / $srcAR;

    $dstImg = imagecreatetruecolor($dstWidth, $dstHeight);

    imagecopyresampled($dstImg, $srcImg, 0, 0, 0, 0, $dstWidth, $dstHeight, $srcWidth, $srcHeight);
    imagejpeg($dstImg, $dstfile);
}

在这种情况下使用这些功能:

$img = imagecreatefromstring(file_get_contents($local));
imagejpeg($img, 'temp.jpg', 100);
thumbFixed($local, 'gallery.jpg', 700, 430);
thumbFixed($local, 'thumbsmall.jpg', 57, 57);
thumbGrid($local, 'grid.jpg', 167);

其中$local保存图像的路径名。

该代码适用于大多数图片,但在一种特殊情况下表现不佳,即 1792x1198、356Kb JPEG 文件。不过,我对这种不当行为感到非常担心,因为我似乎无法以任何方式对其进行跟踪:gdb在 PHP 解释器上运行会导致Program exited with code 0377.(这意味着 PHP 已exit(-1)编辑)而没有其他结果 - 没有堆栈跟踪,没有错误,没有反馈任何。

我发现,通过在每次 libgd 调用之前插入各种回声,脚本$cropImg = imagecreatetruecolor($cropWidth, $cropHeight);thumbFixed函数中执行时会“崩溃”PHP,但我似乎无法解决这个问题,因为我无法从我的代码中控制它,也不从调试器回溯它。有没有人有类似的经历,可以给我一些指示吗?

4

0 回答 0