0

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?

Wonka
  • 8,244
  • 21
  • 73
  • 121

2 Answers2

2

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.

José A. Zapata
  • 1,187
  • 1
  • 6
  • 12
0

The general consensus is that the base64 representation is about 135% of the original image. This can be altered if the string is gzip’ed.

Use couple of images and covert them to base64 with or without gzip and feom that work out a deviation percentage.

nilobarp
  • 3,806
  • 2
  • 29
  • 37
  • Right, I came across that, but I am trying to handle the issue in Laravel specifically due to the exception. Mainly the detecting the PostTooLargeException in Laravel for this image and responding with a graceful error. – Wonka Sep 22 '17 at 19:51