Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get image size (bytes) using PIL

I found out how to use PIL to get the image dimensions, but not the file size in bytes. I need to know the file size to decide if the file is too big to be uploaded to the database.

like image 536
Abdelouahab Pp Avatar asked Aug 10 '12 14:08

Abdelouahab Pp


People also ask

How do you calculate image size in bytes?

1. Multiply the width and height of the image, in pixels, to get the total pixel count. 2. Multiply the total pixel count by 3 to get the image size in bytes.

How do I check the size of a photo in Python?

Use the filesystem API to get the file size, not PIL. or len() , if you have it in memory and not on the filesystem (which seems likely if you're storing as a BLOB in a database.)


2 Answers

Try:

import os print os.stat('somefile.ext').st_size 
like image 194
thebjorn Avatar answered Sep 21 '22 06:09

thebjorn


If you already have the image on the filesystem:

import os os.path.getsize('path_to_file.jpg')` 

If, however, you want to get the saved size of an image that is in memory and has not been saved to the filesystem:

from io import BytesIO img_file = BytesIO() image.save(img_file, 'png') image_file_size = img_file.tell() 

This method will avoid multiple reads of the image data as with StringIO. Note, however, that it will use more RAM. Everything is a tradeoff. :-)

Edit: I just saw this comment from the OP:

finally, the problem is from the beginnig, if someone will upload a picture that have 1 giga (forged one) he'll kill the server before PIL will do its stuff, so i must block the request before it finishs!

This is a very different question, and is probably best accomplished at the web server. For nginx, you can add this to your configuration:

http {     #...         client_max_body_size 100m; # or whatever size you want as your limit     #... } 
like image 34
Scott A Avatar answered Sep 20 '22 06:09

Scott A