简体   繁体   English

Django:上传前调整图片大小

[英]Django: resize image before upload

I want to resize image( Pillow ) before upload, I write code below but doesn't work! 我想在上传前调整图片大小( Pillow ),我在下面编写代码但不起作用! and get error: 并得到错误:

AttributeError at /myapp/list/ / myapp / list /的AttributeError

_committed _committed

Request Method: POST 请求方法:POST

Request URL: http://127.0.0.1:8000/myapp/list/ Django Version: 1.8 Exception Type: AttributeError Exception Value: 请求URL: http//127.0.0.18000 / myapp / list / Django版本:1.8异常类型:AttributeError异常值:

_committed _committed

Exception Location: 例外地点:

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

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

views.py 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)
)
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)

PS for resizing I've used 'python-image-resize' https://github.com/charlesthk/python-resize-image 用于调整大小的PS我使用了'python-image-resize'https: //github.com/charlesthk/python-resize-image

For image resizing you can make use of djanof easy thumbnail library. 对于图像大小调整,您可以使用djanof easy thumbnail库。

Below is the sample code,that i have used in my project 下面是我在项目中使用的示例代码

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

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

There have been some helpful answers, but you might want to understand what is going on with your current code. 有一些有用的答案,但您可能想了解当前代码发生了什么。

Your code raises that exception because of this line : 您的代码因此行而引发该异常:

request.FILES['docfile'] = imga

What is wrong with that ? 这有什么问题? You are affecting a pillow Image object to a django ImageField element. 您正在影响枕头Image对象到django ImageField元素。 Those are two different types and when you call you Document constructor, it might expect to find a file form field that contains a _committed attribute. 这是两种不同的类型,当您调用Document构造函数时,它可能希望找到包含_committed属性的文件表单字段。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM