Python converts a picture to a base64 encoding dump into a database

Source: Internet
Author: User
Tags base64

# _*_ Coding:utf-8 _*_
#中间件: The extension tool traverses the folder, Base64 encodes the folder picture, writes to the database, and reads the lookup method
__author__ = ' wf15038 '
__date__ = "2018/8/28 18:38"

Import Pymysql
Import Sys
From datetime import datetime
Import Base64
Import OS


now = DateTime.Now (). Strftime ('%y-%m-%d%h:%m:%s ')
Def dbinfo ():
conn = ""
conn = pymysql.connect (host= ' IP address ', port=3505, user= "database", password= ' password ', database= ' itportal ',
charset= ' UTF8 ', Cursorclass =pymysql.cursors.dictcursor)
cur = conn.cursor ()
If not cur:
Return "Access db is fail!"
Else
Return conn

Local_dir = ' E:\\xiugai\\ico '
Try
For Root,dirs,files in Os.walk (local_dir):
For filepath in Files:
Image_path = Os.path.join (Local_dir,filepath)
Imagename,_ = Os.path.splitext (filepath)
Print (imagename)
fp = open (Image_path, ' RB ')
Base64_date = Base64.b64encode (Fp.read ())
Fp.close ()
Try
Conn=dbinfo ()
Conncur = Conn.cursor ()
Sql_insertimage= "INSERT into Soft_pt (softname,imstore,submittime) VALUE (%s,%s,%s)"
Conncur.execute (Sql_insertimage, (Imagename,base64_date,now))
Seatdic= Conncur.fetchall ()
Conn.commit ()
Conn.close ()

Except Pymysql. Error as E:
Print ("Error%d%s"% (E.args[0],e.args[1]))
Sys.exit (1)
Except IOError as E:
Print ("Error%d%s"% (E.args[0],e.args[1]))
Sys.exit (1)


Try
conn = Dbinfo ()
Conncur = Conn.cursor ()
Sql_selectimage = "Select Imstore from Soft_pt"
Conncur.execute (Sql_selectimage)
Softpath = Conncur.fetchall ()
Softpathlist = [x[' Imstore '].decode (' GBK ') for x in Softpath]
Print (softpathlist)
For I in Softpathlist:
Print (i)
Conn.commit ()
Conn.close ()

Except Pymysql. Error as E:
Print (e)
Sys.exit (1)

Python converts a picture to a base64 encoding dump into a database

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.