Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Save images into Database with python
- # Your image should be beside your python script
- # Or you can mention the path to your image file
- # A database file will be created instantly
- # Your image will be save in database
- # if you delete your image file
- # you can later retrive the image by using this script and the db file
- # you have to type image name and id number of image
- # Script written by Ayan : ayanu881@gmail.com
- import sqlite3
- DATABASE='image.db'
- conn=sqlite3.connect(DATABASE)
- #creating table
- def createTable():
- command="""CREATE TABLE objectfiles(photoname TEXT NOT NULL, image BLOB);"""
- try:
- conn.execute(command)
- print("Table has been created")
- except:
- print("You already have a safe")
- #converting image file to binary object
- def convertToBinary(filename):
- with open(filename,'rb') as f:
- blobData=f.read()
- return blobData
- #inserting binary into DB
- def insertFile():
- filename=input("Enter name of photo:")
- params=(filename,convertToBinary(filename))
- conn.execute("INSERT INTO objectfiles VALUES(?,?);",params)
- print("inserted !")
- conn.commit()
- #show listed files in db
- def showfiles():
- command="SELECT rowid,photoname FROM objectfiles;"
- cursor=conn.execute(command)
- for row in cursor:
- print('ID:',row[0])
- print('PHOTO:',row[1])
- print()
- #write to hardisk
- def writeFile(blobdata,filename):
- with open(filename,'wb') as f:
- f.write(blobdata)
- print("Success!")
- #image retriving function
- def retriveImage():
- photo_name=input("Enter photo name:")
- id=int(input("Enter id number:"))
- cursor=conn.execute(f"SELECT image FROM objectfiles WHERE rowid={id};")
- for row in cursor:
- writeFile(row[0],photo_name)
- createTable()
- option=''
- while option!='q':
- print("what would like to do")
- print('Press i to store image.')
- print('Press s to show image list.')
- print('Press r to retrive Image.')
- print('Press q to quit')
- option=input('>')
- if option=='i':
- insertFile()
- if option=='s':
- showfiles()
- if option=='r':
- retriveImage()
- if option=='q':
- break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement