通过python将图像插入和检索到mysql中 [英] Inserting and retrieving images into mysql through python

查看:119
本文介绍了通过python将图像插入和检索到mysql中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此代码将图像插入mysql数据库并检索回该图像. 这段代码可以正常工作,没有错误,但是问题甚至是在将图像插入img表后,当我在mysql命令行中执行命令select * from img ;时,它也没有显示记录.

I used this code to insert an image into mysql database and retrieve back the image. This code works perfectly with no errors , but the problem is even after inserting an image into img table , when I execute the command select * from img ; in the mysql command line it shows no records.

在数据库中创建表;
create table img(images blob not null);

Table created in database;
create table img(images blob not null);

import mysql.connector
import sys
from PIL import Image
import base64
import cStringIO
import PIL.Image

db = mysql.connector.connect(user='root', password='abhi',
                              host='localhost',
                              database='cbir')

#image = Image.open('C:\Users\Abhi\Desktop\cbir-p\images.jpg')
with open("C:\Users\Abhi\Desktop\cbir-p\images.jpg", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

#blob_value = open('C:\Users\Abhi\Desktop\cbir-p\images.jpg', 'rb').read()
sql = 'INSERT INTO img(images) VALUES(%s)'    
args = (encoded_string, )
cursor=db.cursor()
cursor.execute(sql,args)
sql1='select * from img'
cursor.execute(sql1)
data=cursor.fetchall()
#print type(data[0][0])
data1=base64.b64decode(data[0][0])
file_like=cStringIO.StringIO(data1)
img=PIL.Image.open(file_like)
img.show()

db.close()

推荐答案

import mysql.connector
import sys
from PIL import Image
import base64
import cStringIO
import PIL.Image

db = mysql.connector.connect(user='root', password='abhi',
                              host='localhost',
                              database='cbir')

image = Image.open('C:\Users\Abhi\Desktop\cbir-p\images.jpg')
blob_value = open('C:\Users\Abhi\Desktop\cbir-p\images.jpg', 'rb').read()
sql = 'INSERT INTO img(images) VALUES(%s)'    
args = (blob_value, )
cursor=db.cursor()
cursor.execute(sql,args)
sql1='select * from img'
db.commit()
cursor.execute(sql1)
data=cursor.fetchall()
print type(data[0][0])
file_like=cStringIO.StringIO(data[0][0])
img=PIL.Image.open(file_like)
img.show()

db.close()

此代码可以正常工作

这篇关于通过python将图像插入和检索到mysql中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆