【问题标题】:Django ImageKit and PILDjango ImageKit 和 PIL
【发布时间】:2015-09-17 22:38:49
【问题描述】:

我正在使用 django 映像并创建自定义处理器。我想找出以 KB(或字节)为单位的大小,但无法这样做。 size 属性给出了文件的尺寸,而不是文件的大小。我是一个新手,所以只能找到 PIL 的 attr 来获取有关图像的更多信息,但它们实际上都没有给出以字节为单位的文件大小。

我已经为 ModelForm 创建了这个处理器。

你能帮忙吗?

我正在添加到目前为止编写的代码。它更像是一个测试代码;

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

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

【问题讨论】:

    标签: python django python-imaging-library pillow django-imagekit


    【解决方案1】:

    在文件的实际路径上使用 os.stat 得到大小(以字节为单位),然后除以 1024 得到 KB:

    import os
    filesize = os.stat('/path/to/somefile.jpg').st_size
    print filesize/float(1024)
    

    【讨论】:

    • 我收到一个错误:强制转换为 Unicode:需要字符串或缓冲区,找到 JpegImageFile
    【解决方案2】:

    以字节为单位的大小会因保存图像的格式而异。例如,如果您使用高度压缩的 JPEG(低质量),则图像会比 PNG 小。

    如果您想在保存到文件之前查看大小,可以将其保存到内存文件中,然后获取大小。

    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)
    

    【讨论】:

      猜你喜欢
      • 2013-04-10
      • 2011-01-23
      • 1970-01-01
      • 2014-06-09
      • 2015-12-12
      • 2015-09-07
      • 2013-07-30
      • 1970-01-01
      • 2012-02-14
      相关资源
      最近更新 更多