基于python和postgreSQL存储图片
生活随笔
收集整理的這篇文章主要介紹了
基于python和postgreSQL存储图片
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
安裝postgresql數據庫python開發包:
apt install libpq-dev python3-dev pip install psycopg2具體代碼如下:
from PIL import Image import psycopg2 as psconn = 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 cataractcur.execute(command)conn.commit()# commit the changescur.close()# close communication with the PostgreSQL database serverconn.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 imagesfor 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 cataractparams = (fname, psycopg2.Binary(img_buffer))cur.execute(command, params)conn.commit()# commit the changescur.close()# close communication with the PostgreSQL database serverconn.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 nameimg_data = rcd[1]#get contentprint (img_name)img = Image.open(BytesIO(img_data))#img.save(img_name)img.show()?
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的基于python和postgreSQL存储图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ubuntu部署postgreSQL数据
- 下一篇: PostgreSQL数据库图像搜索插件i