Advertisement
AyanUpadhaya

Create an Image storing App in Python

Jun 25th, 2021
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.87 KB | None | 0 0
  1. #Image Storing App in Python By Ayan
  2. # ~ First step is going to be creating database and table
  3. # ~ Inserting images in our database
  4. # ~ To insert an image in database we need to convert the image in binary
  5. # ~ Step is to show files that has been added
  6. # ~ Final Step Retrive image file
  7. # ~ Contact : ayanU881@gmail.com
  8.  
  9. import sqlite3
  10. from tabulate import tabulate
  11.  
  12. conn=sqlite3.connect('imagedb.db')
  13. cursor=conn.cursor()
  14.  
  15. def createtable():
  16.     try:
  17.         command="CREATE TABLE objectfiles(photoname TEXT,image BLOB);"
  18.         cursor.execute(command)
  19.         print("database and table created successfully")
  20.     except:
  21.         print("You already have a safe")
  22.  
  23. def convertToBinary(filename):
  24.     with open(filename,'rb') as f:
  25.         data= f.read()
  26.     return data
  27.  
  28.  
  29. def insertImage():
  30.     filename=input("Enter your photoname:")
  31.     params=(filename,convertToBinary(filename))
  32.     cursor.execute("insert into objectfiles values(?,?)",params)
  33.     conn.commit()
  34.     print("Image inserted")
  35.  
  36.  
  37. def showImage():
  38.     command="select rowid,photoname from objectfiles"
  39.     cursor.execute(command)
  40.     result=cursor.fetchall()
  41.     print(tabulate(result))
  42.  
  43. def retriveImage():
  44.     id=input('Enter Image Row id:')
  45.     photoname=input('Enter photoname:')
  46.     command=f"select image from objectfiles where rowid={id};"
  47.     rows=cursor.execute(command)
  48.     for row in rows:
  49.         writeImage(photoname,row[0])
  50.  
  51. def writeImage(filename,blobdata):
  52.     with open(filename,'wb') as file:
  53.         file.write(blobdata)
  54.     print('Success!')
  55.  
  56.  
  57. createtable()
  58.  
  59. run=True
  60. # option='' ~ you actually don't need this
  61.  
  62. while run:
  63.     print("What would you like to do today?")
  64.     print("Press i to insert image ")
  65.     print("Press s to show files")
  66.     print("Press r to retrive image")
  67.     print("Press q to quit application")
  68.     option=input('>')
  69.  
  70.     if option=='i':
  71.         insertImage()
  72.     if option=='s':
  73.         showImage()
  74.     if option=='r':
  75.         retriveImage()
  76.     if option=='q':
  77.         run=False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement