渲染图像而不保存 [英] Render image without saving

查看:49
本文介绍了渲染图像而不保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从用户那里获取图像,在beckend处使用它,然后将结果呈现给用户.是否可以在不将图像保存到磁盘的情况下进行操作?

I want to get an image from user, work with it at beckend and render result back to user. Is it possible to do without saving image on disk?

我的观点:

class InputImageForm(forms.Form):
    image = forms.ImageField()


def get_image(request):
    if request.method == 'POST':
        form = InputImageForm(request.POST, request.FILES)
        if form.is_valid():
            image = request.FILES['image']
            #some actions with image
            return render_to_response('results.html', {'image': image})
        else:
           form = InputImageForm()
    else:
        raise Http404

在模板中,标记{{image}}返回文件名.

In template, tag {{ image }} returns a name of file.

推荐答案

问题是,将页面返回给用户通常会涉及两个请求:一个用于HTML页面,一个用于图像本身(由img引用)在该HTML中标记.但是正如您所说,如果不同时将其存储在任何位置,图像将丢失.

The problem is that returning a page to the user would normally involve two requests: one for the HTML page, and one for the image itself as referenced by an img tag in that HTML. But as you say, without storing it anywhere in the meantime, the image would be lost.

还有另一种选择:您可以使用数据uri 来包含内嵌在html中的图片.这意味着您不必在请求之间保留它,因为所有内容将一并返回.大多数浏览器(包括ie8 +)都支持数据uri.

There is an alternative: you can use a data uri to include the actual data for the image inline in the html. That means you won't have to persist it across requests, as everything will be returned at one. Data uris are supported in most browsers, including ie8+.

您可以这样格式化数据,例如:

You can format the data like this, for example:

from base64 import b64encode

encoded = b64encode(img_data)
mime = "image/jpeg"
uri = "data:%s;base64,%s" % (mime, encoded)

并直接在模板中使用它:

And use it directly in the template:

<img src="{{ uri }}">

这篇关于渲染图像而不保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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