3

Given is on gae using tipfy (python) the following model:

greeting.avatar = db.Blob(avatar)

What is the template-tag to display a blob (here image)?

Wooble
  • 87,717
  • 12
  • 108
  • 131
Daniel Ozean
  • 516
  • 1
  • 6
  • 16

2 Answers2

2

In this case the blob is an an image, which is great. Just use images.get_serving_url(blob_key) and you're happy. I've used this function, and trust me, it is awesome for serving images. Just append =sxx to the url where xx is the pixel size you want. It automatically resizes the image and serves it.

If the blob isn't an image, then you're out of luck w.r.t an easy way out. Maybe use the BlobReader to make a string representation and output it?

If it isn't an image or text, though, what could you possibly want to write to HTML?

Sudhir Jonathan
  • 16,998
  • 13
  • 66
  • 90
  • How is this returned from the handler? The image is broken if I return the serving URL or the URL wrapped in a Response. If I hardcode "/_ah/img/" in the src attribute, it works, but only on development. – Matt Norris Apr 17 '11 at 21:45
  • What do you want to return from the handler? You can either send this back as JSON or render a template. If you're using this handler for serve the image itself, then just send a redirect to the image url. – Sudhir Jonathan Apr 18 '11 at 19:26
  • Serving the image works fine, but trying to return the generated URL and place it in the src attribute didn't work. I ended up using my handler's code to write a simple Jinja filter, which worked perfectly. Thanks for your help! – Matt Norris Apr 19 '11 at 22:41
1

There isn't a built-in template tag for displaying arbitrary data like that. I can think of two approaches:

  1. Write a request handler for serving avatars as images. Based on your example, request handler would just need to look up the greeting to get the image data, send an appropriate Content-Type: image/jpeg (or image/png or whatever) header and then write the blob data to the response stream.

    Then, in your template, you'd display the image like this:

    <img src="/show-avatar/{{ greeting.key().id() }}">
    
  2. Write a custom template tag/template filter that takes the blob data and generates an appropiate data URL, which would encode the image data directly in the HTML document you're generating.

    Then, in your template, you'd display the image something like this:

    <img src="{{ greeting.avatar|dataurl }}">
    

    which would result in output along these lines in the template:

    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IAAAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1JREFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jqch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0vr4MkhoXe0rZigAAAABJRU5ErkJggg==" />
    
Will McCutchen
  • 13,047
  • 3
  • 44
  • 43