Django:上传前调整图片大小

时间:2015-05-25 08:45:11

标签: python django python-imaging-library pillow

我想在上传之前调整图片大小( Pillow ),我写下面的代码却不行! 并收到错误

  

/ myapp / list /

中的AttributeError      

_committed

     

请求方法:POST

     

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

     

_committed

     

例外地点:

     

/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)
)

3 个答案:

答案 0 :(得分:21)

if StartSquare not in (0, 9, 90, 99) and FinishSquare not in (0, 9, 90, 99):

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

答案 1 :(得分:0)

对于图像大小调整,您可以使用djanof easy thumbnail库。

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

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

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

答案 2 :(得分:0)

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

由于以下行,您的代码会引发该异常:

request.FILES['docfile'] = imga

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

相关问题