【问题标题】:python pil image to django imagefield convertpython pil 图像到 django imagefield 转换
【发布时间】:2012-04-29 05:03:45
【问题描述】:

我正在上传图像,图像上传并将其保存在 django 模型中工作得很好。创建缩略图并将其保存到 temp。位置也可以。不起作用的部分是保存缩略图,文件已创建并保存,但它是一个空文件。 :/ 如何解决丢失数据的问题。

如果有人知道如何将 pil 图像转换为 django 模型 - 图像字段而不进行 tmp 保存...请告诉。

def ajax_upload(request):
    if request.method == 'POST':
        newfile = Image()
        newfile.user = request.user
        file_content = ContentFile(request.raw_post_data)
        file_name = request.GET.get('file')

        newfile.image.save(file_name, file_content)

        # thumbnail creation ==========================================
        path = os.path.join(settings.MEDIA_ROOT, newfile.image.url)
        thumb_image = pil_image.open(path)

        # ImageOps compatible mode
        if thumb_image.mode not in ("L", "RGB"):
            thumb_image = thumb_image.convert("RGB")

        thumb_image_fit = ImageOps.fit(thumb_image, (32, 32), pil_image.ANTIALIAS)

        #saving temp file
        tmp_file_path = os.path.join(settings.MEDIA_ROOT, 'tmp_thumbnail.jpg')
        thumb_image_fit.save(tmp_file_path, 'JPEG', quality=75)

        #opening the tmp file and save it to django model
        thumb_file_data = open(tmp_file_path)
        thumb_file = File(thumb_file_data)

        newfile.thumbnail.save(file_name, thumb_file)
        #===============================================================

        results = {'url': newfile.image.url, 'id': newfile.id, 'width': newfile.image.width, 'height': newfile.image.height}
        return HttpResponse(json.dumps(results))
    raise Http404

【问题讨论】:

    标签: django upload thumbnails python-imaging-library django-models


    【解决方案1】:

    您可以保存文件并将其路径(相对于 MEDIA_ROOT)手动分配给目标字段。

    thumb_path = 'uploads/1_small.jpg'
    thumb_image_fit.save(os.path.join(MEDIA_ROOT, thumb_path), 'JPEG', quality=75)
    newfile.thumbnail = thumb_path
    

    当然,您需要手动完成所有 Django 的工作 - 检查文件是否存在,如果存在则修改名称,等等。

    【讨论】:

    • 我现在无法测试它,但 newfile.thumbnail 是一个 ImageField,我不认为 'newfile.thumbnail = thumb_path' 可以。如果我做对了,imagefield 会像这样保存:newfile.thumbnail.save(file_name, thumb_file)(file_name 是一个字符串,thumb_file 必须是一个 File 或 ContentFile)
    • 是的,obj.field.save(name, content) 是更正确和官方记录的方式。但是FileField 仅在数据库中存储一个路径,并允许直接分配该路径。这是未记录的功能,但它可以工作。
    • 谢谢你,我会记住这一点的。
    【解决方案2】:
    from django.core.files.base import ContentFile
    from PIL import ImageOps, Image as pil_image
    import os.path
    import json
    
    
    def ajax_upload(request):
        if request.method == 'POST':
            newfile = Image()
            newfile.user = request.user
            file_content = ContentFile(request.raw_post_data)
            file_name = request.GET.get('file')
    
            newfile.image.save(file_name, file_content)
            newfile.thumbnail.save(file_name, file_content)
    
            #opening and resizing the thumbnail
            path = os.path.join(settings.MEDIA_ROOT, newfile.thumbnail.url)
            thumb_file = pil_image.open(path)
    
            if thumb_file.mode not in ("L", "RGB"):
                thumb_file = thumb_file.convert("RGB")
    
            thumb_image_fit = ImageOps.fit(thumb_file, (100, 100), pil_image.ANTIALIAS)
            thumb_image_fit.save(path)
    
            #===============================================================
    
            results = {
                        'image':
                            {
                                'url': newfile.image.path,
                                'width': newfile.image.width,
                                'height': newfile.image.height
                            },
                        'thumbnal':
                             {
                                'url': newfile.thumbnail.path,
                                'width': newfile.thumbnail.width,
                                'height': newfile.thumbnail.height
                             }
                        }
            return HttpResponse(json.dumps(results))
        raise Http404
    

    【讨论】:

      猜你喜欢
      • 2018-08-10
      • 1970-01-01
      • 2019-07-28
      • 2014-05-21
      • 2019-02-26
      • 2016-11-05
      • 2016-11-06
      • 2020-11-19
      • 2015-12-31
      相关资源
      最近更新 更多