0
0

More than 3 years have passed since last update.

Python3: base64 変換して JSON になった画像を復元

Last updated at Posted at 2021-07-28

次のような JSON を処理します。

{"base64":"/9j//gAkWACmDwAAAAAAA **** "}
decode.py
#! /usr/bin/python
#
#   decode.py
#
#                       Feb/28/2021
# --------------------------------------------------------------------
import sys
import json
import base64
import numpy as np
import cv2
#
file_in = sys.argv[1]
file_image = sys.argv[2]
sys.stderr.write(file_in + "\n")
sys.stderr.write(file_image + "\n")
#
fp_in = open(file_in,encoding='utf-8')
json_str = fp_in.read()
fp_in.close()
#
dict_aa = json.loads(json_str)
data_64 = dict_aa["base64"]
#
sys.stderr.write("len(data) = %d\n" % len(data_64))
#
img_binary = base64.b64decode(data_64)
#
jpg=np.frombuffer(img_binary,dtype=np.uint8)
img = cv2.imdecode(jpg, cv2.IMREAD_COLOR)
cv2.imwrite(file_image,img)
#
# --------------------------------------------------------------------

実行コマンド

./decode.py in01.json out01.jpg

Ubuntu でのライブラリーのインストール

sudo apt install python3-numpy
sudo apt install python3-pip
sudo pip3 install opencv-python
0
0
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
0
0