Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

32
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 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>
32
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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
32
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?