-1

I understand it is most likely impossible, but I'm also open to other suggestions.

The problem here is simple, I have this backend API which receives a list of URLs containing very large images, which then are downloaded, resized, zipped and sent back.

There's a maximum size allowed for all resized images togheter, problem is I'm calculating the size client-side only, so if someone maliciously sends very large images it will probably overload the server memory as all the logic is handled in-memory.

Is there a way for me to validate this server-side? From a list of URLs containing images of no particular pattern/size I want to know if their total size after resizing them will pass a certain limit

I know its possible to know the image size by looking at the content-lenght header, but not sure if I can estimate/calculate the size after resizing, specially not knowing the dimensions.

I'm tagging python and PIL as these are the tools I'm using but I'm not sure if any code is necessary here, its mostly a conceptual question.

Mojimi
  • 2,561
  • 9
  • 52
  • 116

1 Answers1

1
  1. Reject the request if there's no "Content-Length" field or its value exceeds the limit.
  2. Otherwise, download the image and attempt to convert it to a PIL image. If this fails, reject the request.
  3. Check how many bytes there are in one pixel of the image, on average. Then estimate the file size after resizing: estimated_size = requested_width * requested_height * bytes_per_pixel. If the estimated size exceeds the limit, reject the request. Of course, the estimate may be relatively inaccurate, so you may want to account for that by introducing some kind of error margin.
  4. Resize the image, save it to memory, goto (1)
  5. Path the resized images and send them
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • But the important is to know the size of all images togheter before start downloading them – Mojimi Feb 07 '19 at 16:50
  • I guess the only way it to keep track of the total size and abort if it surpasses – Mojimi Feb 07 '19 at 16:50
  • Yeah, that's what I meant by "limit". You can download the images one by one and abort the whole operation (or return the incomplete result) when the total size of the images to be downloaded exceeds this limit – ForceBru Feb 07 '19 at 18:46