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

使用ImageConverter读取数据库图片报Parameter is not valid错误

从数据库读取图片触发"Parameter is not valid"报错排查

问题现象

从数据库读取图片二进制数据转Image对象时,始终触发Parameter is not valid.报错,尝试过MemoryStream等多种实现方案均未解决。

  • 数据表结构截图:表结构截图
  • 表内存储数据示例截图:表数据截图

相关代码

图片写入Python脚本

功能为抓取image字段存储的URL对应图片,将二进制数据写入bImage字段:

import sqlite3
import requests

conn = sqlite3.connect(f'Laptops.db')
c = conn.cursor()
cc = conn.cursor()
s = requests.Session()


def getImage(imgLink):
    headers = {...}
    r = s.get(imgLink, headers=headers, stream=True)

    if r.status_code == 200:
        imgBinary = r.content
        return imgBinary


def executeScriptsFromFile():
    for test in c.execute("SELECT image FROM products"):
        if str(test[0]) != "None":
            imgBinary = getImage(str(test[0]))
            print("d")
            excuteCommand(imgBinary, test[0])
    conn.commit()


def excuteCommand(imgBinary, test):
    cc.execute('''UPDATE products SET bImage = ? WHERE image = ?''', (imgBinary, test))

C#端图片读取代码

执行到ImageConverter.ConvertFrom方法时抛出System.ArgumentException: 'Parameter is not valid.'异常:

SqlDataAdapter myAdapter1 = new SqlDataAdapter(new SqlCommand("select bImage from dbo.Laptops", conn));
DataTable dt = new DataTable();
myAdapter1.Fill(dt);

foreach (DataRow row in dt.Rows)
{
    byte[] imgBytes = ((byte[])row["bImage"]);
    
    ImageConverter imageConverter = new System.Drawing.ImageConverter();
    Image image = imageConverter.ConvertFrom(imgBytes) as Image; // 报错位置

    return image;
}

问题原因与修复方案

  • 核心问题:读写数据源完全不匹配
    Python脚本操作的是本地SQLite数据库文件Laptops.db,写入目标表为products;C#端连接的是SQL Server数据库,读取的是dbo.Laptops表,两边完全是不同的数据源,C#读到的bImage字段根本不是Python写入的图片数据,多为NULL或无效脏数据,解析必然失败。先统一两边连接的数据库实例、表名,确保写入和读取指向同一个存储位置。
  • Python脚本未实际执行写入
    贴出的Python代码仅定义了写入函数,没有任何入口调用executeScriptsFromFile(),就算数据库连接正确,脚本运行后也不会执行任何图片抓取、写入操作,bImage字段会保持默认空值。在脚本末尾加函数调用即可:
    if __name__ == "__main__":
        executeScriptsFromFile()
        conn.close()
    
  • C#端图片解析方式兼容性差
    不要用ImageConverter.ConvertFrom直接转字节数组,该方法对数据完整性校验严格,容错性低,换成官方推荐的MemoryStream读取写法:
    foreach (DataRow row in dt.Rows)
    {
        if (row["bImage"] == DBNull.Value) continue; // 先判空避免强转报错
        byte[] imgBytes = (byte[])row["bImage"];
        using (MemoryStream ms = new MemoryStream(imgBytes))
        {
            Image image = Image.FromStream(ms);
            return image;
        }
    }
    
  • 额外校验项
    • 确认存储字段类型正确:SQLite中bImage字段需为BLOB类型,SQL Server中需为VARBINARY(MAX)类型,禁止用字符串类型字段存储二进制数据,会因字符转码导致图片数据损坏。
    • 写入前校验图片有效性:Python抓取到图片二进制后,可先用PIL库尝试打开验证是合法图片,避免把反爬拦截页、404页面的响应内容当成图片存入数据库。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 05:51:26