PHP GD Allowed memory size exhausted
        Posted  
        
            by gurun8
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by gurun8
        
        
        
        Published on 2010-05-13T15:14:54Z
        Indexed on 
            2010/05/13
            15:34 UTC
        
        
        Read the original article
        Hit count: 322
        
I'm trying to process a directory of JPEG images (roughly 600+, ranging from 50k to 500k) using PHP: GD to resize and save the images but I've hit a bit of a snag quite early in the process. After correctly processing just 3 images (30K, 18K and 231K) I get a Allowed memory size of 16777216 bytes exhausted PHP Fatal error.
I'm cycling through the images and calling the code below:
    list($w, $h) = getimagesize($src);
    if ($w > $it->width) {
        $newwidth = $it->width;
        $newheight = round(($newwidth * $h) / $w);
    } elseif ($w > $it->height) {
        $newheight = $it->height;
        $newwidth = round(($newheight * $w) / $h);
    } else {
        $newwidth = $w;
        $newheight = $h;
    }
    // create resize image
    $img = imagecreatetruecolor($newwidth, $newheight);
    $org = imagecreatefromjpeg($src);
    // Resize
    imagecopyresized($img, $org, 0, 0, 0, 0, $newwidth, $newheight, $w, $h);
    imagedestroy($org);
    imagejpeg($img, $dest);
    // Free up memory
    imagedestroy($img);
I've tried to free up memory with the imagedestroy function but it doesn't seem to have any affect.  The script just keeps consistently choking at the imagecreatefromjpeg line of code.
I checked the php.ini and the memory_limit = 16M setting seems like it's holding correctly.  But I can't figure out why the memory is filling up.  Shouldn't it be releasing the memory back to the garbage collector?  I don't really want to increase the memory_limit setting.  This seems like a bad workaround that could potentially lead to more issues in the future.
FYI: I'm running my script from a command prompt. It shouldn't affect the functionality but might influence your response so I thought I should mention it.
Can anyone see if I'm just missing something simple or if there's a design flaw here? You'd think that this would be a pretty straightforward task. Surely this has to be possible, right?
© Stack Overflow or respective owner