Django/PIL-上传图片后立即保存缩略图版本 [英] Django / PIL - save thumbnail version right when image is uploaded

查看:101
本文介绍了Django/PIL-上传图片后立即保存缩略图版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的表格.py:

class UploadImageForm(forms.ModelForm):
    class Meta:
        model = UserImages
        fields = ['photo']

这是我的模型.py:

class UserImages(models.Model):
    user = models.ForeignKey(User)
    photo = models.ImageField(upload_to=get_file_path)

这是我的观点:

def uploadImageView(request):
    if request.method == 'POST':
        form = UploadImageForm(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.user = request.user
            instance.save()
            return redirect('/')
    else:
        form = UploadImageForm()

    return render(request, 'uploadImagePage.html', {'uploadImageForm': form})

但这只会保存正在上传的图像.如何保存该图像的缩略图版本以及该图像的缩略图版本具有完全相同的名称,但其后带有单词"thumbail"?

But this only saves the image being uploaded. How do I save a thumbnail version of the image as well with the thumbnail version of the image having the exact same name except with the word 'thumbail' after it?

我阅读的教程说我可以做

The tutorials I read said I can do

im = Image.open(infile)
im.thumbnail(size, Image.ANTIALIAS)

要获取缩略图,但就我而言,该图像甚至还没有保存.

to get a thumbnail but in my situation, the image isn't even saved yet.

推荐答案

基于xjtian的答案.这适用于Python 3:

Based on xjtian's answer. This works for Python 3:

import os.path
from PIL import Image
from io import BytesIO
from django.core.files.base import ContentFile
from .my_app_settings import THUMB_SIZE    

class Photo(models.Model):
    photo = models.ImageField(upload_to='photos')
    thumbnail = models.ImageField(upload_to='thumbs', editable=False)

    def save(self, *args, **kwargs):

        if not self.make_thumbnail():
            # set to a default thumbnail
            raise Exception('Could not create thumbnail - is the file type valid?')

        super(Photo, self).save(*args, **kwargs)

    def make_thumbnail(self):

        image = Image.open(self.photo)
        image.thumbnail(THUMB_SIZE, Image.ANTIALIAS)

        thumb_name, thumb_extension = os.path.splitext(self.photo.name)
        thumb_extension = thumb_extension.lower()

        thumb_filename = thumb_name + '_thumb' + thumb_extension

        if thumb_extension in ['.jpg', '.jpeg']:
            FTYPE = 'JPEG'
        elif thumb_extension == '.gif':
            FTYPE = 'GIF'
        elif thumb_extension == '.png':
            FTYPE = 'PNG'
        else:
            return False    # Unrecognized file type

        # Save thumbnail to in-memory file as StringIO
        temp_thumb = BytesIO()
        image.save(temp_thumb, FTYPE)
        temp_thumb.seek(0)

        # set save=False, otherwise it will run in an infinite loop
        self.thumbnail.save(thumb_filename, ContentFile(temp_thumb.read()), save=False)
        temp_thumb.close()

        return True

这篇关于Django/PIL-上传图片后立即保存缩略图版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆