簡體   English   中英

Django:上傳前調整圖片大小

[英]Django: resize image before upload

我想在上傳前調整圖片大小( Pillow ),我在下面編寫代碼但不起作用! 並得到錯誤:

/ myapp / list /的AttributeError

_committed

請求方法:POST

請求URL: http//127.0.0.18000 / 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)
)
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我使用了'python-image-resize'https: //github.com/charlesthk/python-resize-image

對於圖像大小調整,您可以使用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

有一些有用的答案,但您可能想了解當前代碼發生了什么。

您的代碼因此行而引發該異常:

request.FILES['docfile'] = imga

這有什么問題? 您正在影響枕頭Image對象到django ImageField元素。 這是兩種不同的類型,當您調用Document構造函數時,它可能希望找到包含_committed屬性的文件表單字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM