繁体   English   中英

Python - 从 PostgreSQL 保存和恢复图像/图片/JPEG

[英]Python - Saving and Recovering Image/Pictures/JPEG from PostgreSQL

所以,我正在尝试使用 psycopg2 在 Python 中将图像保存到我的 PostgreSQL 表中

插入查询 (Insert.py)

#Folder/Picture is my path/ID is generated/IDnum is increment
picopen = open("Folder/Picture."+str(ID)+"."+str(IDnum)+".jpg", 'rb').read()
filename = ("Picture."+str(ID)+"."+str(IDnum)+".jpg")

#Sample file name is this Picture.1116578795.7.jpg

#upload_name is where I want the file name, upload_content is where I store the image
SQL = "INSERT INTO tbl_upload (upload_name, upload_content) VALUES (%s, %s)"
data = (filename, psycopg2.Binary(picopen))
cur.execute(SQL, data)
conn.commit()

现在要恢复保存的图像,我执行此查询 (recovery.py)

cur.execute("SELECT upload_content, upload_name from tbl_upload")
for row in cur:

    mypic = cur.fetchone()
    open('Folder/'+row[1], 'wb').write(str(mypic[0]))

现在发生的情况是,当我执行 recovery.py 时,它确实生成了一个“.jpg”文件,但我无法查看或打开它。

如果有帮助,我将使用 Python 2.7 和 Centos7。 为了提供更多信息,当我打开生成的文件时,我会在图像查看器上看到它。

Error interpreting JPEG image file (Not a JPEG file: starts with 0x5c 0x78)

我也尝试使用其他格式(.png、.bmp)

我仔细检查了我的数据库类型,显然upload_content 数据类型是文本,它应该是bytea我以为我在创建数据库时已经将它设置为 bytea。 问题解决了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM