python で画像を base64 エンコードする方法のメモ。
プログラム
import sys import io import base64 import json def read_image_file(image_file): with open(image_file, 'rb') as inst: image = inst.read() return image return None def main(): for i in range(1, len(sys.argv)): image_file = sys.argv[i] image = read_image_file(image_file) image_bytes = io.BytesIO(image).read() image_base64 = base64.b64encode(image_bytes).decode('utf-8') obj = { 'id': i, 'image_base64': image_base64, } print(json.dumps(obj, ensure_ascii=False)) return 0 if __name__ == '__main__': res = main() exit(res)
実行結果
$ python image_base64.py img1.jpg img2.jpg {"id": 1, "file_name": "img1.jpg", "image_base64": "/9j/4AA..."} {"id": 2, "file_name": "img2.jpg", "image_base64": "/9j/4AA..."}