简体   繁体   English

Django 保存前调整图像大小

[英]Django Resize Image Before Saving

Goal: Upload a resized image (with same file name and aspect ratio) to AWS S3.目标:将调整大小的图像(具有相同的文件名和纵横比)上传到 AWS S3。

Problem: Currently upon saving, the original image is uploaded and not the resized one.问题:目前在保存时,上传的是原始图像,而不是调整后的图像。

What have I tried?: I've tried multiple different ways to accomplish this but I run into various issues such as not the correct aspect ratio, poor image quality (when using django-resize) etc. The code below seems really close but I just can't seem to find where I am going wrong.我尝试了什么?:我尝试了多种不同的方法来实现这一点,但我遇到了各种问题,例如宽高比不正确、图像质量差(使用 django-resize 时)等。下面的代码看起来非常接近,但我似乎无法找到我要去哪里错了。

models.py模型.py

class Profile(BaseModel):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')


    def save(self, commit=True, *args, **kwargs): #Edited

        if commit:
            img = Image.open(self.image)

            if img.height > 300 or img.width > 300:
                output_size = (300, 300)
                img.thumbnail(output_size)
                img.save(self.image.name, optimize=True, quality=100)

            super().save()

Solution:解决方案:

After a very long time I finally found the answer in this blog .很长一段时间后,我终于在这个博客中找到了答案。

In the end I made a new function in the users/utils.py file:最后我在users/utils.py文件中新建了一个function:

from django.core.files import File
from pathlib import Path
from PIL import Image
from io import BytesIO

image_types = {
    "jpg": "JPEG",
    "jpeg": "JPEG",
    "png": "PNG",
    "gif": "GIF",
    "tif": "TIFF",
    "tiff": "TIFF",
}

def image_resize(image, width, height):
    # Open the image using Pillow
    img = Image.open(image)
    # check if either the width or height is greater than the max
    if img.width > width or img.height > height:
        output_size = (width, height)
        # Create a new resized “thumbnail” version of the image with Pillow
        img.thumbnail(output_size)
        # Find the file name of the image
        img_filename = Path(image.file.name).name
        # Spilt the filename on “.” to get the file extension only
        img_suffix = Path(image.file.name).name.split(".")[-1]
        # Use the file extension to determine the file type from the image_types dictionary
        img_format = image_types[img_suffix]
        # Save the resized image into the buffer, noting the correct file type
        buffer = BytesIO()
        img.save(buffer, format=img_format)
        # Wrap the buffer in File object
        file_object = File(buffer)
        # Save the new resized file as usual, which will save to S3 using django-storages
        image.save(img_filename, file_object)

and then overwrote the save() function in the models.py:然后覆盖 models.py 中的 save() function:

models.py模型.py

from users.utils import image_resize

class Profile(BaseModel):
    #some other fields
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    

    def save(self, commit=True, *args, **kwargs):

        if commit:
            image_resize(self.image, 250, 250)
            super().save(*args, **kwargs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在将图像上传到 firebase 之前调整图像大小 - Resize an image before uploading it to firebase Firebase 调整图像扩展 - Firebase resize image extension Cloud Function:裁剪图像 > 调整为多种尺寸 - Cloud Function: Crop image > Resize to multiple sizes 如何在使用 Active Storage 上传之前调整图像大小(与 AWS 相关) - How to resize images before uploading with Active Storage (linked with AWS) 在 Azure App Service 中为 Django 应用程序保存每日日志 - saving day wise logs in Azure App Service for Django Application 将信息保存到 Firestore 数据库和将图像保存到存储时出现问题 - Problems saving information to Firestore database and image to Storage 将 aws S3 图像位置链接保存到 postgres db 表 - Saving aws S3 image location links to postgres db table 如何在云端使用调整图像 lambda 边缘函数修复 503 错误? - How to fix 503 error with resize image lambda edge functions on cloudfront? Firebase 图像调整扩展。 引用调整大小的图像 - Firebase Image Resize Extension. Referencing the resized images 在将其上传到 s3 之前将 pdf 转换为图像 - Convert pdf to image before uploading it to s3
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM