基于python和postgreSQL存储图片

安装postgresql数据库python开发包:

apt install libpq-dev python3-dev
pip install psycopg2

具体代码如下:

from PIL import Image
import psycopg2 as ps

conn = ps.connect(host="127.0.0.1", user="postgres", password="postgres", database="asoct")#connect postgresql 
if conn is not None:
    cur = conn.cursor()
    command = "create table cataract (name text NOT NULL, content bytea NOT NULL);"#create table cataract
    cur.execute(command)
    conn.commit()# commit the changes
    cur.close()# close communication with the PostgreSQL database server
    conn.close()
import os
#insert and store image with binary format
conn = ps.connect(host="127.0.0.1", user="postgres", password="postgres", database="asoct")#connect postgresql 
if conn is not None:
    cur = conn.cursor()
    image_dir = '/data/fjsdata/ASOCT/Cataract/C_8bit_Crop_New' #the 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 cataract(name, content) values(%s, %s);"#create table cataract
            params = (fname, psycopg2.Binary(img_buffer))
            cur.execute(command, params)
            conn.commit()# commit the changes
    cur.close()# close communication with the PostgreSQL database server
    conn.close()
from io import StringIO,BytesIO 
#query and show image
conn = ps.connect(host="127.0.0.1", user="postgres", password="postgres", database="asoct")#connect postgresql 
if conn is not None:
    cur = conn.cursor() 
    command = "select * from cataract limit 1;"
    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()

 

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值