萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 3 將圖片轉為二進制存入 MySQL BLOB 欄位完整教學

前言:為什麼要把圖片存資料庫?

  • **資料完整性**:圖片與業務資料同交易提交/回滾。
  • **備份簡單**:單一 SQL Dump 即含所有資料。
  • **權限控管**:利用資料庫帳號權限控管存取,避免檔案系統權限分散。
  • **注意**:大量/大檔案建議存檔案系統/物件存儲,資料庫僅存路徑。

資料庫準備

CREATE DATABASE IF NOT EXISTS test CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE test;

CREATE TABLE IF NOT EXISTS Images (
    Id INT PRIMARY KEY AUTO_INCREMENT,
    Data MEDIUMBLOB NOT NULL COMMENT '圖片二進制資料,最大 16MB',
    FileName VARCHAR(255) NOT NULL,
    ContentType VARCHAR(100) NOT NULL,
    FileSize INT UNSIGNED NOT NULL,
    CreatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;
BLOB 型別選擇:TINYBLOB (255B) / BLOB (64KB) / MEDIUMBLOB (16MB) / LONGBLOB (4GB)。圖片建議 MEDIUMBLOB 或 LONGBLOB。

Python 3 完整實作

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
將圖片讀為二進制寫入 MySQL BLOB 欄位
依賴:pip install mysqlclient (或 PyMySQL)
"""

import sys
import mysql.connector  # 或 import pymysql as mysql

# ===== 設定區 =====
DB_CONFIG = {
    'host': 'localhost',
    'user': 'root',
    'password': 'root',
    'database': 'test',
    'charset': 'utf8mb4',
    'autocommit': False
}
IMAGE_PATH = '../web.jpg'  # 相對路徑,請依實際調整
# ===================

def read_image_as_binary(path: str) -> bytes:
    """以二進位模式讀取圖片"""
    try:
        with open(path, 'rb') as f:
            return f.read()
    except IOError as e:
        print(f"[ERROR] 讀取圖片失敗:{e}", file=sys.stderr)
        sys.exit(1)

def insert_image(conn, img_data: bytes, filename: str, content_type: str):
    """寫入資料庫,使用參數化查詢防 SQL Injection"""
    sql = """
        INSERT INTO Images (Data, FileName, ContentType, FileSize)
        VALUES (%s, %s, %s, %s)
    """
    cursor = conn.cursor()
    try:
        cursor.execute(sql, (img_data, filename, content_type, len(img_data)))
        conn.commit()
        print(f"[OK] 圖片已寫入,Id={cursor.lastrowid},大小={len(img_data)} bytes")
    except mysql.connector.Error as e:
        conn.rollback()
        print(f"[ERROR] 寫入失敗:{e}", file=sys.stderr)
        raise
    finally:
        cursor.close()

def main():
    img_bytes = read_image_as_binary(IMAGE_PATH)

    # 偵測 MIME 類型(簡易版)
    import mimetypes
    mime_type, _ = mimetypes.guess_type(IMAGE_PATH)
    if mime_type is None:
        mime_type = 'application/octet-stream'

    try:
        conn = mysql.connector.connect(**DB_CONFIG)
        insert_image(conn, img_bytes, IMAGE_PATH, mime_type)
    except mysql.connector.Error as e:
        print(f"[ERROR] 資料庫連線失敗:{e}", file=sys.stderr)
        sys.exit(1)
    finally:
        if 'conn' in locals() and conn.is_connected():
            conn.close()

if __name__ == '__main__':
    main()

關鍵細節解析

  1. 二進位模式讀檔:open(path, 'rb'),Python 3 bytes 直接對應 MySQL BLOB,無需手動編碼/轉義。
  2. 參數化查詢:cursor.execute(sql, (img_data, ...)),驅動程式自動處理二進位轉義,**嚴禁**字串格式化 ... VALUES ('{img_data}')。
  3. 交易控制:autocommit=False,成功 commit()、失敗 rollback()。
  4. 大檔案分塊寫入:超過 16MB 需用 LONGBLOB + MySQLdb.escape_string 分批寫入或改用 LOAD_FILE()(需檔案在伺服器端)。

讀取並另存圖片驗證

def save_image_from_db(conn, image_id: int, output_path: str):
    cursor = conn.cursor()
    cursor.execute("SELECT Data, FileName FROM Images WHERE Id = %s", (image_id,))
    row = cursor.fetchone()
    cursor.close()
    if row:
        with open(output_path, 'wb') as f:
            f.write(row[0])
        print(f"[OK] 圖片已還原至 {output_path}")
    else:
        print("[WARN] 找不到指定圖片")

效能與架構建議

場景建議
縮圖/小圖 (< 1MB)直接存 BLOB,簡單可靠
大圖/原圖 (> 1MB)存檔案系統/MinIO/S3,DB 存路徑 + 雜湊值
高併發讀取加 CDN/反向代理快取,DB 僅存元資料
備份策略資料庫備份含 BLOB 會極大,建議分離備份或增量備份

結語

Python 3 + mysqlclient/PyMySQL 存取 MySQL BLOB 極為直觀:**二進位讀檔 → 參數化寫入 → 交易提交**。牢記「大檔不存 DB、參數化防注入、交易保一致性」三大鐵律,即可安心管理二進位資料。

copyright © 萬盛學電腦網 all rights reserved