I have a limit of 10MB to accept per image and anything larger should prevent execution of the code. I am not sure how to do so. Here is what I tried:
In the controller method:
// Increase memory limit before processing
ini_set('memory_limit','256M');
$base64_image = $request->get('base64_image');
$image = Image::make($base64_image);
// Returns 0, looks like we have to encode image to get file size...
$image_size = strlen((string) $image);
Log::critical('image_size file size from string: ' . $image_size);
$image = $image->encode('jpg');
// Returns byte size
$image_size = strlen((string) $image);
Log::critical('image_size file size from string: ' . $image_size);
The above works with small images perfectly, but the issue is with large images. I want to detect as early as possible that the size is over the 10MB limit as to not waste any memory/processing time and just return an error to the user that the image is above the allowed file size limit.
When I send a 100MB image as base64, Laravel throws an error of
PostTooLargeException
, since of course the size of the post base64 is huge. So how can I detect that the actual image is over the 10MB limit and return a graceful error to the user if it is?
This line:
$image = Image::make($base64_image);
creates a image resource, and when you cast it to a string it gives you an empty one.
You need to get the length of the actual string, like this:
$image_size = strlen($base64_image);
and check if it's bigger than 10MB.