LoginSignup
30
19

More than 3 years have passed since last update.

【Python】画像ファイルをbase64エンコードしてimg要素で表示する

Posted at

base64エンコードの情報自体は沢山ありますが、base64.b64encodeするだけだとバイナリ型になってしまいます。
そのままimgタグに埋め込むとエンコード文字列がb''に囲まれて画像として認識されません。

.decode('utf-8')してやることで文字列に変換されて、imgタグで表示できるようになります。

import base64
from jinja2 import Environment, FileSystemLoader

def image_file_to_base64(file_path):
    with open(file_path, "rb") as image_file:
        data = base64.b64encode(image_file.read())

    return data.decode('utf-8')

if __name__ == '__main__':

    template_env = Environment(loader=FileSystemLoader('./', encoding='utf8'))
    template_env.globals['image_file_to_base64'] = image_file_to_base64
    template = template_env.get_template('index.tpl')
    html = template.render({
            'image' : 'test.jpg'
    })

    with open('index.html', mode='w', encoding='utf8') as f:
        f.write(html)
index.tpl
<html>
<body>
<img src="data:image/jpeg;base64,{{image_file_to_base64(image)}}" />
</body>
</html>
index.html
<html>
<body>
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/2wBDUFBQUFBQUF~" />
</body>
</html>
30
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
19