开发者

Rendering dynamic images with google app engine

开发者 https://www.devze.com 2023-01-07 07:10 出处:网络
I am working on a Google app engine project where I have saved some images in the datastore. Now I have to resize these images and render them to the template. I have successfully fetched the images

I am working on a Google app engine project where I have saved some images in the datastore. Now I have to resize these images and render them to the template. I have successfully fetched the images but I am not getting,how to render them with other data dictionaries to the template. I am using App engine patch 开发者_开发技巧with GAE.

Following is a code snippet that I am using in my view:

def getData(request,key):
forum = Topic.get(key)
picData = forum.creator.portfolio_set
response = ''
if picData:
    picture = picData[0].userpic
    response = HttpResponse(picture, mimetype="image/jpeg")
    #response['Content-Type'] = 'image/jpeg'
    response['Content-Disposition'] = 'inline'
return render_to_response(request,"forum.html",{"forum":forum,"pic":response })

Now, I am able to render the data within forum variable but not getting how to render the image associated with it. What should I modify in my views file and what should I use in my template to display the image rendered by the views file.

Please suggest.

Thanks in advance.


Solution 1:

Add a generic view to get images e.g. /images/image-id should return image for that ID

def get_image(request, image_id): ....

picture = get from id
return HttpResponse(picture, mimetype="image/jpeg")

Now use image URLs inside your forum.html template, like you would use any normal image URL.

Solution 2: You can directly embed image using data:image see http://en.wikipedia.org/wiki/Data_URI_scheme

so try this

import base64

def getData(request,key):
    forum = Topic.get(key)
    picData = forum.creator.portfolio_set
    pictureSrc = ''
    if picData:
        picture = picData[0].userpic
        pictureSrc = "data:image;base64,%s"%base64.b64encode(picture)

    return render_to_response(request,"forum.html",{"forum":forum,"pic":pictureSrc })
0

精彩评论

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