如何在Django表单中退出照片

m4pnthwp  于 2023-06-25  发布在  Go
关注(0)|答案(2)|浏览(94)

我正在做一个Django项目,我想把图片大小减少到300kb以下,并把图片裁剪到1280px 820px。我们的目标是确保上传的每个图像都是相同的,无论最初的,所以任何最好的解决方案都将受到赞赏。下面是我尝试过的,但没有任何效果。

ALLOWED_EXTENSIONS = ('.gif', '.jpg', '.jpeg')

class PropertyForm(forms.ModelForm): 
    description = forms.CharField(label='Property Description:', max_length=60, widget=forms.TextInput(attrs={'placeholder': 'Briefly Describe your Property. E.g. Bedroom & Palour with Private Detached Bathroom'}))
    state = forms.ChoiceField(choices=Property.STATE_CHOICES, required=False)
    state_lga = forms.CharField(label = 'Local Govt. Area:', max_length=12, widget=forms.TextInput(attrs={'placeholder': 'Enter Local Govt. of Property.'}))
    address = forms.CharField(label = 'Property Address:', max_length=60, widget=forms.TextInput(attrs={'placeholder': 'Enter Street Name with Number and Town Name only.'}))
class Meta:
    model = Property
    fields = ('description', 'address', 'country', 'state', 'state_lga', 'property_type', 'bedrooms', 'bathroom_type', 'price', 'is_available', 'image')

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields['bedrooms'].required = False

def clean_image(self):
    image = self.cleaned_data.get('image')

if image:
    # Check if the image size exceeds 1MB
    if image.size > 1024 * 1024:  # 1MB in bytes
        # Open the image using Pillow
        with Image.open(image) as img:
            # Reduce the image size while preserving the aspect ratio
            max_width = 1920
            max_height = 820
            img.thumbnail((max_width, max_height), Image.ANTIALIAS)

            # Save the modified image with reduced quality to achieve a smaller file size
            buffer = BytesIO()
            img.save(buffer, format='JPEG', optimize=True, quality=85)
            while buffer.tell() > 1024 * 1024:  # Check if file size exceeds 1MB
                quality -= 5
                if quality < 5:
                    break
                buffer.seek(0)
                buffer.truncate(0)
                img.save(buffer, format='JPEG', optimize=True, quality=quality)

            buffer.seek(0)
            image.file = buffer

    # Check file extension for allowed formats
    allowed_formats = ['gif', 'jpeg', 'jpg']
    ext = image.name.split('.')[-1].lower()
    if ext not in allowed_formats:
        raise forms.ValidationError("Only GIF, JPEG, and JPG images are allowed.")
    
    
else:
    raise forms.ValidationError("Please upload an image before submitting the form.")

return image
vfhzx4xs

vfhzx4xs1#

如果你想使用第三方库来处理你想要存档的图像的所有东西,那么你绝对可以使用pypi库。它非常直接,易于使用
链接here

taor4pac

taor4pac2#

我能想到的一种方法是使用PIL。下面的代码片段使用了Models而不是forms,但应该可以做到

#Models.py

from PIL import Image

class Property(models.Model):
    ...
    image = models.ImageField(upload_to='properties_image/')
    ...

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        this_image = Image.open(self.image.path)
        width, height = this_image.size
        TARGET_WIDTH = 1280
        new_height = 820
        this_image = this_image.resize(TARGET_WIDTH,new_height),Image.ANTIALIAS)
        this_image.save(self.image.path,quality=50)

相关问题