claviska / SimpleImage

A PHP class that makes working with images and GD as simple as possible.
MIT License
1.38k stars 383 forks source link

Rotate Image -> Fatal Error Allowed memory size #255

Closed BodyEND closed 4 years ago

BodyEND commented 4 years ago

Hi, i set up maximum size of image (resolution) also maximum file size of image. Everything works fine, but when i am uploading image that is smaller than maximum alowed size but in the same time needs to be rotated because of META TAGS - script is using imagerotate function an it show error

Fatal error: Allowed memory size of ... bytes exhausted (tried to allocate 16384 bytes) in inc/SimpleImage.php on line 867

I think that image will go through IF checks about SIZE and RESOLUTION before resizing and its ok, everything is fine, but in actual resizing SimpleImage detect that image needs to be rorate and imagerotate is probably alocating another memory for rotate image and it exceed total allowed memory .

Please can you help me where i have to put TRY CATCH to PATCH THIS situation?

Probably into function rotate ??? inside SimpleImage.php??

public function rotate($angle, $backgroundColor = 'transparent') { $backgroundColor = $this->allocateColor($backgroundColor);

$this->image = imagerotate(
  $this->image,
  -(self::keepWithin($angle, -360, 360)),
  $backgroundColor
);
imagecolortransparent($this->image, imagecolorallocatealpha($this->image, 0, 0, 0, 127));

return $this;

}

claviska commented 4 years ago

I don't believe this can be caught with try/catch. You may need to do something like this post suggests, as memory management is outside the scope of this library.

If someone provides a definitive solution or workaround I'll be happy to updates the docs.

Hope that helps!

BodyEND commented 4 years ago

Hi, thank you for that link. I searched several pages and found this solution.

In my upload.php file, i just register shutdown function like this:

register_shutdown_function(function(){ $error = error_get_last(); if(null !== $error) { header($_SERVER['SERVER_PROTOCOL'] . '401 Unauthorized', true, 401); echo json_encode(array('error' => 'Error during upload - please resize photo')); exit(); } });

I have most of possible errors covered (resolution, file type and so on), so when something another happen like 'Fatal error: Allowed memory size ...' page just return JSON with 401 response code.

And also you need to hide write errors on page and add @ before variable for manipulating image to force system not show error on page like:

@$manipulate=$image ->fromFile("../photos/tmp/".$imageFile.".jpg") ->autoOrient() ->resize(null,IMG_H_MAX) ->toFile($directoryPath.$imageFile.".jpg", 'image/jpeg',83);

This library for image manipulation is da best.