0
0

More than 1 year has passed since last update.

【Python3】Base64を用いた符号化の復習

Posted at

Base64によるテキストデータと画像ファイルの符号化の復習です。

1.基本

最も単純なもの。コード内で定義された文字列の符号化/復号の確認。

b64_1.py
import base64

plaintext = 'base64'

b64_text = base64.b64encode(plaintext.encode())
print(b64_text)

plaintext = base64.b64decode(b64_text).decode() 
print(plaintext)
  • b64encode()の引数はbytes型であるため、encode()による変換が必要。
  • b64decode()の返り値はbytes型であるため、decode()によってstr型に変換。

b64_1.pyの実行結果は以下の通り。

b'YmFzZTY0'
base64

2.テキストファイルの読み込み

テキストファイルに書かれた文字列の符号化と、テキストファイルに書かれた符号化文字列の復号の確認。

b64_2.py
import base64

filename_r = "plaintext.txt"
filename_w = "b64.txt"

with open(filename_r, "rb") as f:
    b64_text = base64.b64encode(f.read())

with open(filename_w, "wb") as f:
    f.write(b64_text)

with open(filename_w, "rb") as f:
    print(base64.b64decode(f.read()).decode())
  • plaintext.txtには、符号化したい文字列を記載。
  • 符号化文字列はb64.txtに書き込まれ、最後にそれを読み込み、復号。

3.画像ファイルの読み込み

画像ファイルの符号化/復号の確認。

b64_3.py
import base64
import io
import cv2
import numpy as np
from PIL import Image

filename_r = "plainttext.jpg"
filename_w = "b64.txt"
filename_w2 = "result.jpg"

with open(filename_r, "rb") as f:
    b64_text = base64.b64encode(f.read())

with open(filename_w, "wb") as f:
    f.write(b64_text)

with open(filename_w, "rb") as f:
    result = base64.b64decode(f.read())

jpg = np.frombuffer(result, dtype = np.uint8)
img = cv2.imdecode(jpg, cv2.IMREAD_COLOR)
cv2.imwrite(filename_w2, img)
  • plaintext.jpgは符号化したい画像ファイル。
  • 符号化文字列の書き込み先はb64.txt。
  • b64.txtに書き込まれた文字列の復号結果をもとに、result.jpgを作成
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