如何使用python从mysql数据库显示图片? [英] How to display a picture from mysql database using python?

查看:835
本文介绍了如何使用python从mysql数据库显示图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示一张我已经保存在表格img上的图片,但这给我一个错误

I want to display a picture I already saved on the table img, but it gives me an error

无法识别图像文件

cannot identify image file

当尝试打开file_like时. 游标和连接使用到MySQL数据库的连接和密码. 使用以下代码,我想显示图片.这是怎么回事,还是有更好/更简便的方法?

When it try to open the file_like. Cursor and connection use the connection and password to mysql database. With the following code I wanted to display the picture. What's wrong with it, or is there even a better/easier way?

sql1='select * from img'
connection.commit()
cursor.execute(sql1)
data2=cursor.fetchall()

file_like=cStringIO.StringIO(data2[0][0])

img1=PIL.Image.open(file_like,mode='r').convert('RGB')
img1.show()
cursor.close()

推荐答案

使用io.BytesIO代替cstringIO时,它可以很好地工作,而且无需解码和编码.而且我还将类型从blob更改为mediumblob,从而可以显示更大的图片.

When using io.BytesIO instead of cstringIO it works fine, also without decoding and encoding. And I also changed type from blob to mediumblob, which allows bigger pictures.

import pymysql
import io
from PIL import Image

connection=pymysql.connect(host="localhost",
                 user="root",
                 passwd="root",
                 db="test")
cursor=connection.cursor()
sql1 = 'select * from table'
cursor.execute(sql1)
data2 = cursor.fetchall()

file_like2 = io.BytesIO(data2[0][0])

img1=Image.open(file_like2)
img1.show()
cursor.close()
connection.close()

这篇关于如何使用python从mysql数据库显示图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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