在django中上传到s3之前如何压缩图像? [英] how to compress the image before uploading to s3 in django?
本文介绍了在django中上传到s3之前如何压缩图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发一个用户可以上传图像的应用程序.我想将图像大小减小200-500kb. 这是我的models.py文件
I am working on an application where a user can upload an image. I want to reduce the size of the image in 200-500kb. This is my models.py file
class Report_item(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL)
title = models.CharField(max_length=255, help_text='*Title for the post e.g. item identity')
image = models.ImageField(default="add Item image",
upload_to=get_uplaod_file_name)
def __str__(self):
return self.title + " " + str(self.publish)
这是我的views.py文件
And this is my views.py file
class ReportCreate(generic.CreateView):
model = Report_item
fields = ['title','image']
def get_form(self, form_class=None):
if form_class is None:
form_class = self.get_form_class()
form = super(ReportCreate, self).get_form(form_class)
form.fields['title'].widget = TextInput(
attrs={'placeholder': '*Enter UID e.g. CBSE Marksheet Roll nunber 0506***'})
return form
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.owner = self.request.user
self.object.save()
return FormMixin.form_valid(self, form)
我正在使用Django 1.11和S3存储.请在上传到s3之前帮助我压缩图像.
I am using Django 1.11 and S3 storage. Kindly help me to compress the image before uploading to s3.
推荐答案
因此,我们需要在模型中定义一个save方法,以便在保存之前压缩图像.以下代码可以帮助我解决问题.
So we need to define a save method in models in order to compress the image before save. Following code help me what I want to achieve for my problem.
class Report_item(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL)
title = models.CharField(max_length=255, help_text='*Title for the post e.g. item identity')
image = models.ImageField(default="add Item image",
upload_to=get_uplaod_file_name)
def save(self):
# Opening the uploaded image
im = Image.open(self.image)
output = BytesIO()
# Resize/modify the image
im = im.resize((100, 100))
# after modifications, save it to the output
im.save(output, format='JPEG', quality=90)
output.seek(0)
# change the imagefield value to be the newley modifed image value
self.image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.image.name.split('.')[0], 'image/jpeg',
sys.getsizeof(output), None)
super(Report_item, self).save()
借助此5 Mb图像,压缩到大约4 kb.
WIth the help of this 5 Mb image compress to 4 kb approx.
这篇关于在django中上传到s3之前如何压缩图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文