PHP 在调整图像大小时内存不足


PHP running out of memory when resizing images

我编写了一个脚本来尝试将图像的尺寸重新调整为目标(在我的示例中为 25kb)。但是有时我会得到

Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 5529 bytes)

在此过程中。也许有一些技术(我尝试了unset())来释放这个循环中的空间。

private function resizeTo($target){
    $x = 9;
    for($x; $x > 0; $x--){
        // Expose w/h from $this->info
        list($width, $height) = $this->info;
        $newWidth = $width * $x / 10;           
        $newHeight = ($height / $width) * $newWidth;
        $tmp = imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($tmp, $this->image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
        if (file_exists($this->finalPath)) 
            unlink($this->finalPath);
        imagepng($tmp, $this->finalPath);
        if(filesize($this->finalPath) <= $target) return true;
        else unset($tmp);
    }
    $this->error = "Could not resize to $target kb after 10 attempts. Please upload a smaller image.";
}

图片来自 $_FILES[] 的表单上传。

难以辨别的部分是它会在 200kb 的图像上失败,但传递 330 kb 的(特定)图像。所以我不确定确切的原因或传入的文件大小决定了失败。

如果我们希望认为对图像进行一次重新采样是可以的,那么您应该尝试执行imagedestroy($tmp);而不是取消设置。还没有测试它如何影响内存,但实际上应该破坏资源。