2017-09-21 68 views
0

簡單地說,我希望獲取在數據庫中的所有156個存儲的圖像和產生的HTML鏈接,如「<img src ...../> "MySQL的編碼轉換成HTML

我的代碼工作在提取數據庫中的圖像和觀看他們極大的。但是當我開始測試base64編碼,我收到以下錯誤

return binascii.a2b_base64(s) 
binascii.Error: Incorrect padding 

這裏是代碼:

import MySQLdb 
import base64 
db = MySQLdb.connect(host="localhost", # your host, usually localhost 
        user="test",   # your username 
        passwd="test", # your password 
        db="test") 
cur = db.cursor() 


cur.execute("SELECT * FROM attachments") 

#looping through row 4 where all blobs are located 

for row in cur.fetchall(): 
    blob_read = row[4] 

#(error happen here while decoding) 

    decoding = blob_read.decode('base64') 
    print '<img src="data:image/jpg;base64,"'+ decoding + '/>' 

    filename = row[2] 

#(extracted the files to test if images are corrupted; they are not) 

     with open(filename, 'wb') as output_file: 
     output_file.write(blob_read) 

db.close() 

回答

0

一杯咖啡做的工作= d 我再次偷看數據庫,發現附件表不僅有圖片,而是在html/text,image/jpeg,video/3gpp,audio/amr。因此,它解釋了上述錯誤。

所以我只加處理圖像/ JPEG的另一個迴路調整了劇本

這裏是沒有清理等

import MySQLdb 
import base64 
db = MySQLdb.connect(host="localhost", # your host, usually localhost 
        user="test",   # your username 
        passwd="test", # your password 
        db="test") 
cur = db.cursor() 

cur.execute("SELECT * FROM attachments") 
count = 0 

for row in cur.fetchall(): 
     if row[1] == "image/jpeg": 
      blob_read = row[4] 
      image = blob_read 
      output = base64.encodestring(image) 
      print output 
      print 
      print 
      print "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" 
      print 
      print 
      filename = row[2] 
      with open(filename, 'wb') as output_file: 
       output_file.write(blob_read) 
       count = count + 1 
     else: 
      pass 




print count 

db.close() 
解決方案