不为别的,只为做一个连自己都羡慕的人

python实现图片与base64之间的转换

1. base64转图片

def select_all_picture():
    db = connSqlite()
    cursor = db.cursor()
    title_sql = "select * from news_picture"
    try:
        cursor.execute(title_sql)
        data = cursor.fetchall()
        for key in data:
            import os, base64
            # img_data = bytes(key[2], 'gb2312')
            img_data = base64.b64decode(key[2].replace("data:image/jpeg;base64,", ""))
            # 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
            with open('./picture/{}.jpg'.format(key[1]), 'wb') as f:
                f.write(img_data)
            print('successful')
    except Exception as err:
        print(err)

2. 图片转base64

def downImg(img_url):
    print(img_url)
    img_binary = requests.get(img_url, headers=headers, proxies=proxies)  # .content  # 获取图片的二进制格式
    content_type = img_binary.headers["Content-Type"].split('/')[1]
    print(content_type)
    print(img_binary.status_code)
    if img_binary.status_code == 200:
        base64_data = base64.b64encode(img_binary.content)
        # print(img_binary)
        s = base64_data.decode()
        s_base64 = 'data:image/jpeg;base64,%s' % s
  else:
        s_base64 = ''
    return s_base64
posted @ 2021-12-03 13:55  升级打怪  阅读(2349)  评论(0编辑  收藏  举报