Django ImageKit and PIL

冷暖自知 提交于 2019-12-11 18:02:36

问题


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']

回答1:


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)



回答2:


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)


来源:https://stackoverflow.com/questions/32641051/django-imagekit-and-pil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!