LoginSignup
62
43

More than 3 years have passed since last update.

[Python]Base64でエンコードされた画像データをデコードする。

Last updated at Posted at 2019-01-22

目的

Base64でエンコードされた画像データをデコードします。

投稿理由

Base64で画像をエンコードするプログラムは探せばよくありますが、
デコードして得た画像を保存するプログラムは探した限り見つからなかった為投稿しました。

使用言語

Python3.7.0

Base64で画像をエンコードする

エンコードする画像

image001.jpg

エンコードするためのプログラム

import base64

#Base64でエンコードする画像のパス
target_file=r"original.jpg"
#エンコードした画像の保存先パス
encode_file=r"encode.txt"

with open(target_file, 'rb') as f:
    data = f.read()
#Base64で画像をエンコード
encode=base64.b64encode(data)
with open(encode_file,"wb") as f:
    f.write(encode)

Base64でデコードして画像を保存する。

デコードする文字列(さっきの画像をエンコードした文字列)

image.png

デコードするためのプログラム

import cv2
import base64
import numpy as np
import io

#Base64でエンコードされたファイルのパス
target_file=r"encode.txt"
#デコードされた画像の保存先パス
image_file=r"decode.jpg"

with open(target_file, 'rb') as f:
    img_base64 = f.read()

#バイナリデータ <- base64でエンコードされたデータ  
img_binary = base64.b64decode(img_base64)
jpg=np.frombuffer(img_binary,dtype=np.uint8)

#raw image <- jpg
img = cv2.imdecode(jpg, cv2.IMREAD_COLOR)
#画像を保存する場合
cv2.imwrite(image_file,img)

#表示確認
cv2.imshow('window title', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

デコードして得られた画像

image.png
正しく画像がデコードされました!

62
43
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
62
43