将图像写入 Django HttpResponse() 的最佳方法 [英] Best way to write an image to a Django HttpResponse()

查看:15
本文介绍了将图像写入 Django HttpResponse() 的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要向经过验证的用户安全地提供图像(即它们不能作为静态文件提供).我目前在我的 Django 项目中有以下 Python 视图,但它似乎效率低下.有什么更好的方法吗?

I need to serve images securely to validated users only (i.e. they can't be served as static files). I currently have the following Python view in my Django project, but it seems inefficient. Any ideas for a better way?

def secureImage(request,imagePath):
    response = HttpResponse(mimetype="image/png")
    img = Image.open(imagePath)
    img.save(response,'png')
    return response

(图片是从 PIL 导入的.)

(Image is imported from PIL.)

推荐答案

嗯,有时需要重新编码(即在图像上应用水印,同时保持原始图像不变),但对于最简单的情况,您可以使用:

Well, re-encoding is needed sometimes (i.e. applying an watermark over an image while keeping the original untouched), but for the most simple of cases you can use:

try:
    with open(valid_image, "rb") as f:
        return HttpResponse(f.read(), content_type="image/jpeg")
except IOError:
    red = Image.new('RGBA', (1, 1), (255,0,0,0))
    response = HttpResponse(content_type="image/jpeg")
    red.save(response, "JPEG")
    return response

这篇关于将图像写入 Django HttpResponse() 的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆