【问题标题】:ImageField from Django to PIL Image to send via HttpResponseImageField 从 Django 到 PIL Image 通过 HttpResponse 发送
【发布时间】:2016-11-06 02:33:35
【问题描述】:

您好,我是 Django 的新手(而且我的母语不是英语)。我正在尝试从数据库(ImageField)中获取图像(我使用表单通过 POST 获取图像的 ID),使用 PIL Image 对其进行裁剪并通过 HttpResponse 发送。它没有给出错误,但是当我收到图像“piece.jpg”时,它是一个损坏的文件。如果我使用记事本打开它,我只能看到:

    <PIL.Image.Image image mode=RGB size=46x75 at 0x3DEA790>

这是我在views.py中的代码:

    from PIL import Image

    def function(request):

        if request.method == 'POST':

            id = request.POST.get('id')
            object = Document.objects.get(pk=id)

            im = Image.open(object.docfile)

            left = 10
            top = 10
            right = 100
            bottom = 100
            cropped_image = im.crop( (left, top, right, bottom) )

            response = HttpResponse(cropped_image, content_type='image/jpg')
            response['Content-Disposition'] = 'attachment; filename="piece.jpg"'
            return response

我尝试只发送“object.docfile”并且它有效。但是如果我尝试发送“im”(这是一个 PIL 图像),它就不起作用了。

我需要通过HttpResponse 发送它,因为我希望它可以在该页面上下载。

【问题讨论】:

    标签: python django image python-imaging-library crop


    【解决方案1】:

    HttpResponse 需要字符串或迭代器。文档中的更多详细信息:

    https://docs.djangoproject.com/en/1.9/ref/request-response/#django.http.HttpResponse.init

    你尝试过这样的事情吗?

    response = HttpResponse(mimetype='image/jpg')
    cropped_image.save(response, "JPEG")
    return response
    

    【讨论】:

      【解决方案2】:

      这帮助我找到了解决方案!您的代码在浏览器中打开图像(这没关系,因为我没有说我想要它作为下载)。要获得下载对话框,代码是:

          response = HttpResponse(content_type='image/jpg')
          cropped_image.save(response, "JPEG")
          response['Content-Disposition'] = 'attachment; filename="piece.jpg"'
          return response
      

      谢谢先生 :)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-06-30
        • 1970-01-01
        • 2012-04-29
        • 2021-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多