问题描述
完全不知道如何在将图像上传到S3存储桶之前对其进行压缩。
我尝试将以下内容添加到我的save()
方法中:
def save(self,*args,**kwargs):
# Opening the uploaded image (if it was uploaded)
if self.receipt:
im = Image.open(self.receipt)
output = BytesIO()
# Resize/modify the image
im = im.convert('RGB')
# after modifications,save it to the output
im.save(output,format='JPEG',quality=80)
output.seek(0)
# change the imagefield value to be the newley modifed image value
self.receipt = InMemoryUploadedFile(output,'ImageField',"%s.jpg" % self.receipt.name.split('.')[0],'image/jpeg',os.sys.getsizeof(output),None)
super(Expense,self).
这种方法不是很忠实,因为只要更新/创建Expense
实例就运行save方法。因此,如果附加了收据(图像文件),并且我更新了实例上的任何其他字段,则会将另一个图像文件添加到我的S3存储桶中。
我尝试添加
if self.receipt and self.pk is None
因此save()
方法仅在新实例上运行-但是,如果文件添加到现有Expense
实例中,我也想对其进行压缩。
我听到了很多关于动态执行压缩的lambda函数的讨论,但是找不到有关如何设置它的任何不错的指南。
如果有帮助,我正在使用django-storages
。
(为澄清起见,上传文件和所有文件都工作正常,我只希望将实际上传的文件压缩为1)存储空间,2)更快的加载/保存,实际的图像质量并不重要)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)