简体   繁体   中英

Insert images to cassandra using python

I'm new in cassandra and python. I'm trying to insert images in a table in cassandra using python. I want to see the image I'm inserting and the same image after I retrive from the database.

import cassandra; 
print cassandra.__version__  #3.4.1
from cassandra.cluster import Cluster
cluster = Cluster(['127.0.0.1:9042']) # TEST CLUSTER 127.0.0.1:9042

session = cluster.connect('prueba')

#Open the image file on lecture and binary mode 
file = open('gato.jpg', 'rb') #file = open('gato.jpg', 'r')
print file
print type(file) #file

imagen_gato = file.read()
print type(imagen_gato) #str

#r_data = binascii.unhexlify(imagen_gato.strip())
#print type(r_data) 

stream = io.BytesIO(imagen_gato) 
print type(stream) #<type '_io.BytesIO'>

I see that the image is rigth

#Let's show the image just loaded
import Tkinter as tk
from PIL import ImageTk, Image

#This creates the main window of an application
window = tk.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')

#path = 'gato.jpg'
file = open('gato.jpg', 'rb') #dont know why i need to do this again
#Creates a Tkinter-compatible photo image, which can be used everywhere                                     Tkinter expects an image object.
#img = ImageTk.PhotoImage(Image.open(path))
img = ImageTk.PhotoImage(Image.open(file))

#The Label widget is a standard Tkinter widget used to display a text or     image on the screen.
panel = tk.Label(window, image = img)
#The Pack geometry manager packs widgets in rows or columns.
panel.pack(side = "bottom", fill = "both", expand = "yes")
#Start the GUI
window.mainloop()

I try to insert the file in the casandra table and retrive it (HERE IS THE ERROR)

#guardamos dicho archivo en cassandra
print 'Last Successfull print'
session.execute(  #ON THIS LINE IS THE ERROR
    """
    INSERT INTO fotos (id_foto, imagen )
    VALUES (%s, %s)
    """,
    (1,imagen_gato)
)
print 'Success'


#imprimimos dicho archivo desde casandra
print 'retrive'
rows = session.execute('SELECT id_foto, imagen FROM fotos')
for foto_row in rows:
    #print foto_row.id_foto, foto_row.imagen
    file2 = foto_row.imagen
print 'Success2'

Then I try to print again the image

#This creates the main window of an application
window = tk.Tk()
window.title("Join2")
window.geometry("300x300")
window.configure(background='grey')

#path = 'gato.jpg'

#Creates a Tkinter-compatible photo image, which can be used everywhere     Tkinter expects an image object.
img = ImageTk.PhotoImage(Image.open(file2))

#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
panel = tk.Label(window, image = img)
#The Pack geometry manager packs widgets in rows or columns.
panel.pack(side = "bottom", fill = "both", expand = "yes")
#Start the GUI
window.mainloop()

but I got an error

d4b4a173636c461a8911bb30cdcd9041aa7d4c8950f4239645bf335afe19fe55fc6ff008d31216f3
3066a6e3b8cb82727e2e72cd4434314266e453f73ffd9272c200909312c20277573756172696f203
127290a09'; java.nio.charset.MalformedInputException: Input length = 1">

I got no idea how to make this work, or why there is and error. I supouse it is the format of the image, that cassandra takes blob ,

below is my directory structure for my example

[vagrant@casstest ImageInsert]$ ll
total 24
-rw-rw-r--. 1 vagrant vagrant  1128 May 22 10:15 Cass.py
-rw-rw-r--. 1 vagrant vagrant 17715 Sep 13  2019 sample.jpg

Below is Cass.py which will insert image into cassandra

import base64
from cassandra.cluster import Cluster
cluster = Cluster(['192.168.0.85'])

#create session
session = cluster.connect()

# create keyspace "event" and table "blobtest" if not exist
session.execute("CREATE KEYSPACE IF NOT EXISTS event WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}  AND durable_writes = true;")
session.execute("CREATE TABLE IF NOT EXISTS event.blobtest ( Name varchar PRIMARY KEY, Image blob)")

#will print your cassandra version
print(session.execute("SELECT release_version FROM system.local").one())

# convert local image into base64
image = open('sample.jpg', 'rb') #open binary file in read mode 
image_read = image.read()
image_64_encode = base64.encodestring(image_read)

# define which keyspace/database to use for further query
session.execute('USE event')

strCQL = "INSERT INTO blobtest (Name,Image) VALUES (?,?)"
pStatement = session.prepare(strCQL)
session.execute(pStatement,["Sample",image_64_encode])

# print binary data of image from query
print(session.execute("SELECT * FROM blobtest").one())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM