代码之家  ›  专栏  ›  技术社区  ›  Mo Chan

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

  •  2
  • Mo Chan  · 技术社区  · 7 年前

    因此,我试图使用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]))
    

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

    如果有帮助的话,我将使用Python 2.7和Centos7来完成。 为了获得更多信息,当我打开生成的文件时,我在图像查看器上获得了这些信息。

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

    我还尝试使用其他格式(.png,.bmp)

    1 回复  |  直到 7 年前
        1
  •  1
  •   Mo Chan    7 年前

    我仔细检查了我的数据库类型,显然upload\u content datatype是 文本 应该是这样的 二进制数据 当我创建db时,我想我已经将它设置为bytea了。问题已解决。