php图像复制/裁剪/调整内存限制

时间:2012-09-17 18:23:12

标签: php image-processing gd

  

可能重复:
  PHP rebuilding images: memory usage

我有一个简单的图片上传脚本。允许用户上传最大文件大小为10MB的图像(gif,jpg或png)。还允许用户应用作物 图像,所以我将脚本的内存限制设置为256MB。我认为256MB的内存足以裁剪10MB的图像。我错了。 当用户上传大图像(大约5000x5000)并且几乎没有裁剪它时,脚本总是会抛出内存不足错误。我发现this neat tool有助于确定使用php调整图像大小时的内存限制。我也遇到了这个公式

$width * $height * $channels * 1.7

确定图像需要多少内存。我正在寻找有人来解释这里发生了什么。我很清楚,一个10MB的jpeg 加载到内存时不是10MB,但我如何确定它将占用多少内存?上面的公式是否正确?是否有更有效的方法来裁剪大图像 或者我是否必须使用大量内存?

对于任何感兴趣的人,这里是裁剪图像的代码。

function myCropImage(&$src, $x, $y, $width, $height) {
    $src_width = imagesx($src);
    $src_height = imagesy($src);

    $max_dst_width = 1024;
    $dst_width = $width;

    $dst_height = $height;
    $max_dst_height = 768;

    // added to restrict size of output image.
    // without this check an out of memory error is thrown.
    if($dst_width > $max_dst_width || $dst_height > $max_dst_height) {
        $scale = min($max_dst_width / $dst_width, $max_dst_height  / $dst_height);
        $dst_width *= $scale;
        $dst_height *= $scale;
    }

    if($x < 0) {
        $width += $x;
        $x = 0;
    }
    if($y < 0) {
        $height += $y;
        $y = 0;
    }

    if (($x + $width) > $src_width) {
        $width = $src_width - $x;
    }

    if (($y + $height) > $src_height) {
        $height = $src_height - $y;
    }

    $temp = imagecreatetruecolor($dst_width, $dst_height);
    imagesavealpha($temp, true);
    imagefill($temp, 0, 0, imagecolorallocatealpha($temp, 0, 0, 0, 127));
    imagecopyresized($temp, $src, 0, 0, $x, $y, $dst_width, $dst_height, $width, $height);

    return $temp;
}

0 个答案:

没有答案
相关问题