开发者

Generating images at runtime with Python

开发者 https://www.devze.com 2023-03-19 09:49 出处:网络
Long story short...I have a base64 encoded string that I retrieve from a database. I need to output an image from the encoded data but without saving the file. Is it possible to outpu开发者_开发知识库

Long story short...I have a base64 encoded string that I retrieve from a database. I need to output an image from the encoded data but without saving the file. Is it possible to outpu开发者_开发知识库t the image through a python script? (by changing the header or something like that)?


import urllib

uri = 'data:image/jpg;base64,' + urllib.quote(raw_data)
    return(or print depending what you're using - anyway, render to html) '<img src="'+uri+'"/>'

not entirely cross-browser, IE not working, raw data needs to be base64 encoded


Have a look at the Tkinter PhotoImage Class. It can take base64 encoded images and display them.


Serve the image data at a different URL with proper HTTP headers (Content-Type) and use that URL in the HTML code that should display it. Details depend on the framework you are using (Django? CGI? own HTTP server?).

It should be something like this (imaginary framework):

def return_record_from_db(key):
    "called for the '/item/${key}' URI"
    item = database.get(key)
    return Response("<h1>{0} <p>The image:<img src='/item/{1}/image'>"
                                                  .format(item.name, key))

def return_image_for_db_record(key):
    "called for the '/item/${key}/image' URI"
    item = database.get(key)
    return Response(binascii.a2b_base64(item.image), extra_headers="Content-Type: image/jpg")
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号