Skip to content
Advertisement

PHP – imagecreatefromjpeg uses 100M memory for <1M image

The image is less than 1MB but the size is roughly 5500×3600. I am trying to resize the image down too something less than 500×500. My code is pretty simple.

    $image = imagecreatefromjpeg("upload/1.jpg");
    $width = imagesx($image);
    $height = imagesy($image);
    $pWidth = 500;
    $pHeight =  334;
    $image_p = imagecreatetruecolor($pWidth, $pHeight);
    setTransparency($image,$image_p,$ext);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $pWidth, $pHeight, $width, $height);

I found out that to process this image, the imagecreatefromjpeg uses 100M using memory_get_usage.

Is there a better way to do imagecreatefromjpeg? is there a workaround or a different function that uses less memory?

I did ask my server admins to increase the memory but I doubt they will increase it to 100M or more. I am considering limiting the dimensions of an image a user can upload but not before exhausting all my options as users will most likely upload images they took.

Btw, the following is the image i used which uses 100M of memory

enter image description here

Advertisement

Answer

What @dev-null-dweller says is the correct answer:

With 5500×3600 you will need at least 5500*3600*4 bytes in memory =~ 80MB. For large pictures Imagick extensions might have better performance than GD

There is no way to “improve” on that because that’s the amount of memory needed to process the image. JPEG is a compressed format so its file size is irrelevant, it’s the actual dimensions that count. The only way to deal with such an image inside GD is increasing the memory limit.

You may be able to do better using a library/command line client like ImageMagick if you have access to that – when you run ImageMagick from the command line, its memory usage won’t count towards the memory limit. Whether you can do this, you’d need to find out from your web host or server admin.

Another idea that comes to mind is using an image resizing API that you send the image to. That would take the load completely off your server. This question has some pointers: https://stackoverflow.com/questions/5277571/is-there-a-cdn-which-provides-on-demand-image-resizing-cropping-sharpening-et

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement