基于python将数字图片存储到postgreSQL中

import os
from PIL import Image
import psycopg2 as ps
from io import StringIO, BytesIO

def table_exist(table_name=None, conn=None):
    if conn is not None:
        cur = conn.cursor()
        try:
            cur.execute("select to_regclass(" + "\'" + table_name + "\'" + ") is not null")
            rows = cur.fetchall()
        except Exception as e:
            rows = []
            conn.close()
        if rows:
            data = rows
            flag = data[0][0]
            return flag

# 1. connect postgresql
conn = ps.connect(host="localhost", user="jiangshan", password="jiangshan", database="imgdb", port="5432")
table_name = "img_tb"

# 2. CREATE TABLE IF table IS NOT EXIST
# 查询出来的表是否存在的状态,存在则为True,不存在则为False
table_flg = table_exist(table_name, conn)
if table_flg is False:
    cur = conn.cursor()
    # command = "DROP TABLE public.{0} CASCADE".format(table_name)# -- 删除表
    command = "CREATE TABLE IF NOT EXISTS {0} (name text NOT NULL, content bytea NOT NULL);".format(table_name)
    cur.execute(command)
    conn.commit()
    # cur.close()  # close communication with the PostgreSQL database server
    # conn.close()

# 3. insert and store image with binary format
if conn is not None:
    cur = conn.cursor()
    image_dir = '/imgae_data/beijing'# path of images
    for fname in sorted(os.listdir(image_dir)):
        if fname.endswith(".jpg"):
            #open the image file
            with open(os.path.join(image_dir, fname),'rb') as reader:
                img_buffer = reader.read()
            command = "insert into {0} (name, content) values(%s, %s);".format(table_name)
            params = (fname, ps.Binary(img_buffer))
            cur.execute(command, params)
            conn.commit()# commit the changes
    # cur.close()# close communication with the PostgreSQL database server
    # conn.close()

# 4. query and show image
if conn is not None:
    cur = conn.cursor()
    command = "select * from {0} limit 1;".format(table_name)
    cur.execute(command)
    rcd = cur.fetchone()
    img_name = rcd[0]#get name
    img_data = rcd[1]#get content
    print(img_name)
    img = Image.open(BytesIO(img_data))
    #img.save(img_name)
    img.show()

    cur.close()  # close communication with the PostgreSQL database server
    conn.close()

  

posted @ 2021-06-04 16:19  土博姜山山  阅读(229)  评论(0编辑  收藏  举报