- Base64 是什麼?簡單說明
- 如何把圖片轉成 Base64?
- 如何還原 Base64 成圖片?(含實例與驗證)
1. Base64 是什麼?
- Base64 是一種編碼方式,可以把二進位(如圖片、音檔、檔案)轉成純文字(ASCII)。
- 常用在資料傳輸、嵌入 HTML、JSON 時避免二進位資料亂碼。
- 例如:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA...
這是一張 PNG 圖片的 Base64 表示。
2. 如何把圖片轉成 Base64?
用 Python 範例
假設有一張圖:example.png

code:
import base64
with open("example.png", "rb") as img_file:
b64_str = base64.b64encode(img_file.read()).decode('utf-8')
print(b64_str[:100]) # 只顯示前100字元
3. 如何還原 Base64 成圖片?
用 Python 還原 & 驗證
假設 b64_str
是你的 Base64 字串:
import base64
b64_str = "你的Base64內容"
with open("restored.png", "wb") as out_img:
out_img.write(base64.b64decode(b64_str))
這會生成一個還原後的圖片檔案 restored.png
。
打開後會發現跟原圖一模一樣!
小結
- Base64 方便讓圖片(或其他二進位資料)以文字形式儲存與傳輸。
- 可以完全還原原始圖片。
- 適合嵌入 JSON、HTML、Markdown 等純文字環境。
推薦hahow線上學習python: https://igrape.net/30afN

1. 流程總覽
假設你有一張圖片檔案 img.png
,流程如下:
(A) 讀取圖片(二進位)
with open("img.png", "rb") as img_file:
img_bytes = img_file.read()
# img_bytes 型別:<class 'bytes'>
(B) 編碼成 Base64
import base64
b64_bytes = base64.b64encode(img_bytes)
# b64_bytes 型別:<class 'bytes'> (Base64字串的bytes型態)
(C) 轉成字串(如果要存成 JSON 或顯示)
b64_str = b64_bytes.decode('utf-8')
# b64_str 型別:<class 'str'>
(D) 還原:Base64 字串 → 圖片 bytes
restored_bytes = base64.b64decode(b64_str)
# restored_bytes 型別:<class 'bytes'>
(E) 存回圖片檔案
with open("restored.png", "wb") as out_file:
out_file.write(restored_bytes)
2. 型別總結對照表

code:
import base64
# 步驟A:讀取圖片檔案
with open("img.png", "rb") as img_file:
img_bytes = img_file.read()
print("A:", type(img_bytes)) # <class 'bytes'>
# 步驟B:Base64 編碼
b64_bytes = base64.b64encode(img_bytes)
print("B:", type(b64_bytes)) # <class 'bytes'>
# 步驟C:轉成字串
b64_str = b64_bytes.decode('utf-8')
print("C:", type(b64_str)) # <class 'str'>
# 步驟D:Base64 解碼
restored_bytes = base64.b64decode(b64_str)
print("D:", type(restored_bytes)) # <class 'bytes'>
# 步驟E:寫回還原圖檔
with open("restored.png", "wb") as out_file:
out_file.write(restored_bytes)
4. 流程圖解
img.png
→ 讀檔 →bytes
bytes
→ Base64 encode →bytes
(Base64)bytes
→ decode(‘utf-8’) →str
(Base64字串)str
→ Base64 decode →bytes
bytes
→ 寫檔 →restored.png
推薦hahow線上學習python: https://igrape.net/30afN
img_file.read() 型別是bytes
base64.b64encode( img_file.read() )
型別 也是bytes
差異為何?
import base64
import os
dirname = r"D:\Temp"
basename = "example.png"
path = os.path.join(dirname, basename)
if os.path.exists(path):
with open(path, "rb") as img_file:
# 讀取原始bytes
raw_bytes = img_file.read()
print("原始bytes前20個字節:\t", raw_bytes[:20])
# 將原始bytes轉換為base64編碼的bytes
b64_bytes = base64.b64encode(raw_bytes)
print("base64編碼bytes前20個字節:\t", b64_bytes[:20])
# 簡單比較
print("\n主要差別:")
print("1. 原始bytes可能包含不可打印字符,如控制字符和特殊字節")
print("2. base64編碼後只包含A-Z, a-z, 0-9, +, / 和 = 這些可打印字符")
print("3. base64編碼後的大小約為原始數據的4/3")
else:
print("File not found:", path)
輸出結果:

推薦hahow線上學習python: https://igrape.net/30afN
近期留言