Reputation: 699
I am using django image and creating a custom processor. I want to find out the size in KB (or bytes) but unable to do so. The size attribute give the dimensions and not the size of the file. I am a newbie so have only been able to find attr of PIL to get more information about the image but none of the them actually give the file size in bytes.
I have creating this processor for a ModelForm.
Can you please help with this?
I am adding the code written so far. It is more of a test code;
import urllib
import os
class CustomCompress(object):
def process(self, image):
print 'image.width',image.width
print 'image.height',image.height
print 'image.size', image.size
print 'image.info', image.info
print 'image.tobytes', image.tobytes
print 'image.category', image.category
print 'image.readonly', image.readonly
print 'image.getpalette', image.getpalette
st = os.stat(image).st_size
print 'get_size ', st
return image
Here is the forms.py
class PhotoForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(PhotoForm, self).__init__(*args, **kwargs)
self.fields['old_image'] = ProcessedImageField(spec_id='myapp:test_app:old_image',
processors=[CustomCompress()],
format='JPEG',
# options={'quality': 60}
)
class Meta:
model = Photo
fields = ['old_image']
Upvotes: 0
Views: 460
Reputation: 1740
The size in bytes will vary depending of the format in which the image will be saved. For example if you use highly compressed JPEG (low quality) the image will be smaller than PNG.
If you want to see the size before save it to file you can save it to in memory file and then get the size.
from io import BytesIO
class CustomCompress(object):
def process(self, image):
jpeg_file = BytesIO()
png_file = BytesIO()
image.save(jpeg_file, format='JPEG')
image.save(jpeg_file, format='PNG')
jpeg_size = len(jpeg_file.getvalue())
png_size = len(png_file.getvalue())
print('JPEG size: ', jpeg_size)
print('PNG size: ', png_size)
Upvotes: 0
Reputation: 18222
use os.stat on the actual path of the file to get the size in bytes, then divide by 1024 to get KB:
import os
filesize = os.stat('/path/to/somefile.jpg').st_size
print filesize/float(1024)
Upvotes: 1