-1

I want to the image size of an image in megabyte or kilobyte. This type of question has been asked before and a solution wasn't really provided. NOTE:i'm not concerned with the image width and height, just the file size in megabyte or kilobytes because i'm working on the image for user input validation so its on the fly.

This is my code:

from PIL import Image

images = request.FILES.getlist('files')
memory_upload = []
         for x in range(len(images)):
            img = images[x]
            #image upload input validator for extension
            if img.name.split('.')[1] in accept_ext:
            im = Image.open(img)
            print(im.size)

The result for the images in size in pillow is in width and height format: (3696, 4620) But i need to know the size in megabytes so as to prevent the image from being compressed if the file is huge to restrict something like a DoS attack on the server

Xcode
  • 11
  • 2

1 Answers1

0
file = request.FILES['filename']
file.name           # Gives name
file.content_type   # Gives Content type text/html etc
file.size           # Gives file's size in byte
file.read()         # Reads file

You can also restrict django file upload limits. Using these settings.

Ref: https://docs.djangoproject.com/en/4.0/ref/settings/#file-upload-settings

DEFAULT_FILE_STORAGE
FILE_UPLOAD_HANDLERS
FILE_UPLOAD_MAX_MEMORY_SIZE
FILE_UPLOAD_PERMISSIONS
FILE_UPLOAD_TEMP_DIR
MEDIA_ROOT
MEDIA_URL
DATA_UPLOAD_MAX_MEMORY_SIZE¶
Default: 2621440 (i.e. 2.5 MB).

The maximum size in bytes that a request body may be before a SuspiciousOperation (RequestDataTooBig) is raised. The check is done when accessing request.body or request.POST and is calculated against the total request size excluding any file upload data. You can set this to None to disable the check. Applications that are expected to receive unusually large form posts should tune this setting.

The amount of request data is correlated to the amount of memory needed to process the request and populate the GET and POST dictionaries. Large requests could be used as a denial-of-service attack vector if left unchecked. Since web servers don’t typically perform deep request inspection, it’s not possible to perform a similar check at that level.

Msvstl
  • 1,116
  • 5
  • 21
  • Thanks for this. You're a life saver just figured out a path using img.size/1024/1024 > 6.1. But your solution is way better. Thanks for the help – Xcode Jul 28 '22 at 15:22
  • Just had to read more on the answer. For anyone who wants to implement the solution, the issue with setting FILE_UPLOAD_MAX_MEMORY_SIZE is that it is already preset and even if you extend it. An higher file size would be read as a TempUploadFile which if the size of the file wasn't more than the FILE_UPLOAD_MAX_MEMORY_SIZE would be saved as an InMemoryUploadFile, so you still need input validation. And you can use *(img.size/1024/1024) < {your_image_size_limit} – Xcode Jul 28 '22 at 15:37