<img src="data:..."> で画像を指定する方法のメモ。
python で <img src="data:..."> で画像を指定するプログラムを作成してみました。
■サーバ
■html
上記のサーバに "http://localhost:8000/" でアクセスした際のレスポンスは以下のようになります。
python で <img src="data:..."> で画像を指定するプログラムを作成してみました。
■サーバ
import sys import requests import io import base64 from PIL import Image from flask import Flask, jsonify app = Flask(__name__) def image_base64(bytes): inst = io.BytesIO(bytes) img = Image.open(inst).convert('RGB') inst.close() outst = io.BytesIO() img.save(outst, format='PNG') img_data = outst.getvalue() outst.close() img_base64 = base64.b64encode(img_data).decode('utf-8') return img_base64 @app.route('/') def view_html(): img_url = 'https://www.xgoo.jp/top2018/public/img/img_socialmark.png' res = requests.get(img_url) img_base64 = image_base64(res.content) html = f''' <html> <head> <meta http-equv="Content-Type" content="text/html; charset=utf-8"> </head> <body> <img src="data:image/png;base64,{img_base64}"> </body> </html> ''' return html if __name__ == '__main__': app.run(host='0.0.0.0', port=8000)
■html
上記のサーバに "http://localhost:8000/" でアクセスした際のレスポンスは以下のようになります。
<html> <head> <meta http-equv="e;Content-Type"e; content="e;text/html; charset=utf-8"e;> </head> <body> <img src="data:image/png;base64,..."> </body> </html>