0

I would like to pass raw image data in TurboGears2 to the mako template to use in an img tag

(ie., scr=data:image/jpg,base64,${imagedata}).

The image is retrieved from sql server image format

I have been struggling to do this as everything passed to the template is in unicode and I get "UnicodeDecodeError:'ascii' codec can't decode byte..." when the template trys to open it.

This would save considerable time on mulitple calls to the /image?image#x.jpg.

stuartz
  • 121
  • 4
  • 9

1 Answers1

3

The following works when modifying a quickstart'ed TurboGears 2.2.2-based project, configured to use the Mako templating system. First I made a few changes to example/controllers/root.py:

# …
from tg import config
import os
import base64

class RootController(BaseController):
    # …
    def _file_to_base64(self, path):
        with open(path, 'r') as stream:
            image_data = base64.b64encode(stream.read())

        return 'data:image/{0};base64,{1}' \
               .format(path.rsplit('.', 1)[-1].lower(), image_data)

    @expose('example.templates.index')
    def index(self):
        """Handle the front-page."""

        filename = os.path.join(config['paths']['static_files'],
                                'images', 'turbogears_logo.png')

        return dict(page='index', image_data=self._file_to_base64(filename))

Then the code in the make template becomes:

<img src="${image_data}" />

The above code was tested using Python 2.7.3. I do not know how your database image format, or encoding, differs from the data getting loaded from a plain image file.

Martin Thorsen Ranang
  • 2,394
  • 1
  • 28
  • 43
  • I know I answered this late, but if the answer works for you, it would be great if you accept it as the answer – so that other users can benefit from knowing that the answer works. If you had any issues, please let me know. – Martin Thorsen Ranang Dec 08 '15 at 20:57