首先是直接把图片显示出来,采用下面的方式
import requests
def download_img(imgurl):
try:
rsp = requests.get(imgurl)
if rsp.status_code == 200:
content = rsp.content
# 注意下面open里面的mode是"wb+", 因为content的类型是bytes
with open("./a.jpg", "wb+") as f:
f.write(content)
return str(content)
except Exception, err:
print 'load img err. err=', err
download_img("https://i.loli.net/2020/12/23/lkET5OzDHqsdh3Z.jpg")
如果是要将图片bytes格式转化为base64编码,再转化成string类型存储进数据库,可以采用base64进行转化
import base64
def downloadimg(imgurl):
try:
rsp = requests.get(imgurl)
if rsp.status_code == 200:
content = rsp.content
content = base64.b64encode(content) # 将图片转化成base64格式
return str(content)
except Exception, err:
print 'load img err. err=', err
downloadimg("https://i.loli.net/2020/12/23/lkET5OzDHqsdh3Z.jpg")
原文链接:https://blog.csdn.net/weixin_46129834/article/details/111595776
网友评论