0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python初心者】Base64エンコードとデコードの基本まとめ

Posted at

今回は、バイナリデータや文字列をBase64という形式に変換したり、元に戻したりする方法について学んだことをまとめました。Base64は、データを安全に送受信するために使われる形式の一つです。

Base64とは?

Base64とは、バイナリデータ(画像・音声・ファイルなど)を、ASCII文字だけで表現できるように変換する方法のひとつです。URLやメールなどでデータを扱いやすくするために使われます。

Base64エンコード(base64.b64encode()

まずは、文字列をBase64にエンコードしてみます。エンコードするには、最初にバイト型に変換してから b64encode() を使います。

import base64

original = "hello world"
original_bytes = original.encode("utf-8")

encoded_bytes = base64.b64encode(original_bytes)
encoded_str = encoded_bytes.decode("utf-8")

print(encoded_str)
aGVsbG8gd29ybGQ=

Base64デコード(base64.b64decode()

Base64文字列を元のデータに戻すには b64decode() を使います。

import base64

encoded_str = "aGVsbG8gd29ybGQ="
decoded_bytes = base64.b64decode(encoded_str)
decoded_str = decoded_bytes.decode("utf-8")

print(decoded_str)
hello world

バイナリデータ(画像など)にも使える

Base64は文字列だけでなく、バイナリファイル(画像や音声など)にも使えます。たとえば画像をBase64にエンコードするときは次のようになります。

with open("image.png", "rb") as f:
    image_data = f.read()

encoded = base64.b64encode(image_data)
print(encoded[:60])  # 先頭だけ表示
b'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABFklEQVQ4T6WTsQ2DMAxF3'

Base64の用途例

  • メール添付ファイルのエンコード
  • JSONなどでバイナリデータを含むとき
  • Basic認証のユーザー名+パスワードのエンコード
  • Web APIでの画像データの送受信

おわりに

Base64はバイナリデータを文字列として扱うための基本的な方法です。画像や音声などをWeb経由で送信したり、認証情報を一時的に扱うときに使われる場面が多いようなので、基礎だけでも覚えておこうと思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?