简体   繁体   English

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

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

So, I'm trying to save an image into my PostgreSQL table in Python using psycopg2所以,我正在尝试使用 psycopg2 在 Python 中将图像保存到我的 PostgreSQL 表中

INSERT Query (Insert.py)插入查询 (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()

now to recover the saved Image I perform this query (recovery.py)现在要恢复保存的图像,我执行此查询 (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]))

now what happens is when I execute the recovery.py it does generate a ".jpg" file but I can't view or open it.现在发生的情况是,当我执行 recovery.py 时,它确实生成了一个“.jpg”文件,但我无法查看或打开它。

If it helps I'm doing it using Python 2.7 and Centos7.如果有帮助,我将使用 Python 2.7 和 Centos7。 for the sake of additional information, I get this on the image viewer when I open the generated file.为了提供更多信息,当我打开生成的文件时,我会在图像查看器上看到它。

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

I also tried using other formats as well (.png, .bmp)我也尝试使用其他格式(.png、.bmp)

I double checked my database type and apparently upload_content datatype is text its supposed to be bytea I thought I already had it set to bytea when I created my db.我仔细检查了我的数据库类型,显然upload_content 数据类型是文本,它应该是bytea我以为我在创建数据库时已经将它设置为 bytea。 Problem solved.问题解决了。

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

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