[英]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.