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

I wrote a script to try and re-size the dimensions of an image to a target (25kb in my example). However sometimes I am getting

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

during the process. Maybe there is some technique (I tried unset()) to free up space during this loop.

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.";
}

The image comes from a form upload in $_FILES[].

The hard-to-discern part is it will fail on an image that is 200kb, but pass on an (particular) image that is 330 kb.. So I'm not sure what the exact reason or incoming file size determines the failure.

If we hopefully think that one resampling of image is ok than you should try to do imagedestroy($tmp); instead of unset. Haven't tested how it's affects memory it but should actually destroy resource.