0

我在保存图像之前尝试调整大小并转换 mime

模型.py

class ProductImages(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    image_type = models.CharField(max_length=33,default='image_type')    
    image_file = models.ImageField(
        upload_to=upload_to_path,
        null=True,
        blank=True,
        default='magickhat-profile.jpg'
    )

    def save(self, *args, **kwargs):
        #on update image delete old file
        try:
            this = ProductImages.objects.get(id=self.id)
            if this.image_file != self.image_file:
                this.image_file.delete(save=False)
        except:
            pass 
        super().save(*args, **kwargs)
        image_manipulation(self)

函数upload_to_path and image_manipulation已导入from utils.utils import upload_to_path, image_manipulation

实用程序/utils.py

from PIL import Image
from pathlib import Path

def upload_to_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = instance.product.slug+"_"+str(instance.id)+"."+ext
    return 'user_{0}/{1}/{2}'.format(instance.product.user.id, instance.product.id, filename)

def image_manipulation(self):
    pathx = self.image_file.path
    self.image_file = Image.open(pathx)
    img_x = self.image_file.resize((200,300))
    img_x.save(pathx)

使用此代码工作,但我没有实现此代码以转换为png...

当我尝试类似:

def image_manipulation(self):
    pathx = self.image_file.path
    self.image_file = Image.open(pathx)
    img_x = self.image_file.resize((200,300))
    img_rgb = img_x.convert('RGB')
    img_split_ext = pathx.rsplit( ".", 1 )[ 0 ]
    img_rgb.save(img_split_ext+".png")

当我进行此更改时,文件被上传、调整大小和转换,但初始文件(jpg)也被上传。如果可能的话,我很感激如果我能解释一下这个过程的流程,在一个可调用的那个,接收方法本身的upload_to2 个参数之间,因为从我的 pov 来看是关于数据库中的记录,并且是关于文件系统存储......(instance, filename)save()upload_tosave()

你能看到吗,我很困惑

4

0 回答 0