python 向mysql中存儲圖片以及讀取圖片
轉載自:http://www.cnblogs.com/sherlockhua/archive/2012/03/29/2423786.html
python2.0
Python 操作 MySQL 數據庫
https://www.runoob.com/python/python-mysql.html
(十二)插入圖片
有人喜歡使用mysql來存儲圖片,而有的人喜歡把圖片存儲在文件系統中。而當我們要處理成千上萬的圖片時,會引起技術問題。圖片時二進制數據,mysql有種特殊的數據類型,用來存儲二進制數據,叫做BLOB(Binary Large Ojbect)。
開始之前,我們創建一個images表用來存儲圖片數據,代碼如下:
mysql> CREATE TABLE Images(Id INT PRIMARY KEY AUTO_INCREMENT, Data MEDIUMBLOB);
Query OK, 0 rows affected (0.06 sec)
接着,我們讀取圖片數據,並把它插入到數據庫中,示例代碼如下:
#!/usr/bin/python # -*- coding: utf-8 -*- import MySQLdb as mdb import sys try: fin = open("chrome.png") img = fin.read() fin.close() except IOError, e: print "Error %d: %s" % (e.args[0],e.args[1]) sys.exit(1) try: conn = mdb.connect(host='localhost',user='testuser', passwd='test623', db='testdb') cursor = conn.cursor() cursor.execute("INSERT INTO Images SET Data='%s'" % \ mdb.escape_string(img)) conn.commit() cursor.close() conn.close() except mdb.Error, e: print "Error %d: %s" % (e.args[0],e.args[1]) sys.exit(1)
首先,我們打開一個圖片,並讀取圖片數據,代碼如下:
fin = open("chrome.png")
img = fin.read()
接着,我們把圖片數據插入到數據庫中,並使用escape_string進行特殊字符串轉義。代碼如下:
cursor.execute("INSERT INTO Images SET Data='%s'" % \
mdb.escape_string(img))
(十三)讀取圖片
上一節中,我們把圖片存儲到數據庫中了,在本節,我們將取回並保存為圖片文件。本節示例如下:
#!/usr/bin/python # -*- coding: utf-8 -*- import MySQLdb as mdb import sys try: conn = mdb.connect(host='localhost',user='testuser', passwd='test623', db='testdb') cursor = conn.cursor() cursor.execute("SELECT Data FROM Images LIMIT 1") fout = open('image.png','wb') fout.write(cursor.fetchone()[0]) fout.close() cursor.close() conn.close() except IOError, e: print "Error %d: %s" % (e.args[0],e.args[1]) sys.exit(1)
首先,我們從數據庫中讀取一張圖片數據:
cursor.execute("SELECT Data FROM Images LIMIT 1")
接着,我們以二進制的寫方式打開一個文件,寫入圖片數據:
fout = open('image.png','wb')
fout.write(cursor.fetchone()[0])
執行程序,我們當前目錄應該有一張圖片,驗證一下是否和寫入數據庫之前的圖片一致。
python3 操作方法:
//讀取