You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将图片属性获取函数的结果存入本地数据库?

实现图片信息存入数据库的方案

1. 先修正原代码的小问题

原代码存在函数定义位置不合理、变量作用域可能报错的问题,先调整代码结构,把图片信息整理成统一格式方便后续存储:

import os
from colorthief import ColorThief
from PIL import Image

os.chdir("x")

def rgb_to_hex(domcol):
    return str("#%02x%02x%02x" % domcol).upper()

def get_details():
    image_info_list = []
    for f in os.listdir("x"):
        if f.endswith(".jpg"):
            i = Image.open(f)
            fn, fext = os.path.splitext(f)
            filename = f"{fn}{fext}"
            width = i.width
            height = i.height
            ct = ColorThief(f)
            dominant_color = ct.get_color(quality=1)
            dominant_color_hex = rgb_to_hex(dominant_color)
            
            # 把单张图片的信息封装成字典
            image_info = {
                "filename": filename,
                "width": width,
                "height": height,
                "dominant_color": dominant_color_hex
            }
            image_info_list.append(image_info)
            print(f"已提取信息:{filename}")
    return image_info_list

2. 用SQLite实现存储逻辑

SQLite是轻量型数据库,无需额外安装服务,适合快速实现需求:

2.1 初始化数据库表

先创建用于存储图片信息的表结构:

import sqlite3

def init_db():
    # 连接数据库(不存在则自动创建文件)
    conn = sqlite3.connect("image_info.db")
    cursor = conn.cursor()
    
    # 创建表,包含自增ID、文件名、宽度、高度、主色调字段
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS image_details (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            filename TEXT UNIQUE NOT NULL,
            width INTEGER NOT NULL,
            height INTEGER NOT NULL,
            dominant_color TEXT NOT NULL
        )
    ''')
    conn.commit()
    conn.close()

2.2 将图片信息插入数据库

编写批量插入的函数,同时处理重复文件的情况:

def save_to_db(image_info_list):
    conn = sqlite3.connect("image_info.db")
    cursor = conn.cursor()
    
    for info in image_info_list:
        try:
            # 用占位符插入数据,避免SQL注入
            cursor.execute('''
                INSERT INTO image_details (filename, width, height, dominant_color)
                VALUES (?, ?, ?, ?)
            ''', (info["filename"], info["width"], info["height"], info["dominant_color"]))
        except sqlite3.IntegrityError:
            # 文件名已存在时跳过
            print(f"{info['filename']} 已存在于数据库,跳过存储")
    
    conn.commit()
    conn.close()

3. 完整执行流程

整合所有函数,执行提取+存储的完整流程:

if __name__ == "__main__":
    init_db()
    image_data = get_details()
    save_to_db(image_data)
    print("所有图片信息已完成存储")

可选扩展说明

  • 如果需要使用MySQL/PostgreSQL等数据库,只需替换sqlite3的连接与操作代码(比如用pymysql或psycopg2),核心逻辑保持一致。
  • 若要避免重复数据,除了依赖表的UNIQUE约束,也可以先查询数据库,再决定插入或更新现有记录。

内容的提问来源于stack exchange,提问作者kone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 00:15:43