【问题标题】:Django: resize image before uploadDjango:在上传前调整图像大小
【发布时间】:2015-08-06 16:44:15
【问题描述】:

我想在上传之前调整图像大小(枕头),我在下面写了代码但不起作用! 并得到错误:

/myapp/list/ 处的 AttributeError

_提交

请求方法:POST

请求网址:http://127.0.0.1:8000/myapp/list/ Django 版本:1.8 异常类型:AttributeError 异常值:

_提交

异常位置:

/usr/local/lib/python3.4/dist-packages/Pillow-2.8.1-py3.4-linux-x86_64.egg/PIL/Image.py

getattr 中,第 622 行 Python 可执行文件:/usr/bin/python3.4 Python 版本:3.4.0

views.py

def list(request):
# Handle file upload
if request.method == 'POST':
    form = DocumentForm(request.POST, request.FILES)
    if form.is_valid():
        imga = request.FILES['docfile']
        size = (600, 400)
        im = Image.open(imga)
        imga = im.resize(size)
        request.FILES['docfile'] = imga
        newdoc = Document(docfile = request.FILES['docfile'], namefile=request.POST['namefile'])
        newdoc.save()

        # Redirect to the document list after POST
        return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
else:
    form = DocumentForm() # A empty, unbound form

# Load documents for the list page
documents = Document.objects.all()

# Render list page with the documents and the form
return render_to_response(
    'myapp/list.html',
    {'documents': documents, 'form': form},
    context_instance=RequestContext(request)
)

【问题讨论】:

  • 与您的问题无关,而是与问题的标题有关:您知道您正在服务器端调整图像大小,因此技术上 上传之后(而不是之前)。

标签: python django python-imaging-library


【解决方案1】:
from PIL import Image
from io import BytesIO
from django.core.files.base import ContentFile
from resizeimage import resizeimage

class SomeModel(models.Model):
    image = models.ImageField(upload_to=your_get_file_path_callback)

    def save(self, *args, **kwargs):
        pil_image_obj = Image.open(self.image)
        new_image = resizeimage.resize_width(pil_image_obj, 100)

        new_image_io = BytesIO()
        new_image.save(new_image_io, format='JPEG')

        temp_name = self.image.name
        self.image.delete(save=False)  

        self.image.save(
            temp_name,
            content=ContentFile(new_image_io.getvalue()),
            save=False
        )

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

附:为了调整大小,我使用了 'python-image-resize' https://github.com/charlesthk/python-resize-image

【讨论】:

  • 分配self.image = new_image_io会发生什么
【解决方案2】:

对于图像大小调整,您可以使用 djanof 简单的缩略图库。

以下是我在项目中使用的示例代码

options = {'size': (200, 200), 'crop': True}
thumb_url =get_thumbnailer(image path).get_thumbnail(options).url

供参考https://github.com/SmileyChris/easy-thumbnails

【讨论】:

    【解决方案3】:

    有一些有用的答案,但您可能想了解当前代码的情况。

    由于这一行,您的代码引发了该异常:

    request.FILES['docfile'] = imga
    

    这有什么问题?您正在将枕头 Image 对象影响到 django ImageField 元素。这是两种不同的类型,当您调用 Document 构造函数时,它可能希望找到包含 _committed 属性的文件表单字段。

    【讨论】:

      猜你喜欢
      • 2017-06-26
      • 2013-10-03
      • 1970-01-01
      • 2013-11-29
      • 2015-06-19
      • 2011-10-24
      • 1970-01-01
      相关资源
      最近更新 更多