# -*- coding: utf-8 -*-
# __author__ = SHI
import os
import re
import base64
def findimg(content):
'''
查找网页中所有的img,类似img src='1.png',返回1.png
:param content: 网页内容
:return: 返回找到的所有图片文件名列表
'''
patt = re.compile('<img src="(.+)" ') #正则表达式查找所有的img
grp = re.findall(patt,content)
# print(grp)
return grp
def findcomment(content):
'''
查找注释,删除注释
:param content: 网页源内容
:return: 删除注释后的网页内容
'''
patt = re.compile('(<!--.+-->)')
grp = re.findall(patt,content)
# print(grp)
for g in grp:
content = content.replace(g,'')
return content
def imgbase64(pic_path):
'''
实现图片的base64编码,返回编码字符串
:param pic_path:
:return:
'''
pic_basename = os.path.basename(pic_path)
file_ext = pic_basename.split('.')[-1].lower()
# print(file_ext)
if file_ext == "jpg" :
tag = "jpg"
elif file_ext == "jpeg" :
tag = "jpg"
elif file_ext == "png" :
tag = "png"
elif file_ext == "bmp" :
tag = "bmp"
else:
print("Unsupported image format !")
return None
with open(pic_path, "rb") as imageFile:
str_pic = base64.b64encode(imageFile.read()).decode('ascii')
# print(str_pic)
str_begin = 'data:image/' + tag + ';base64,'
result_str = str_begin + str_pic
# print(result_str)
return result_str
def readhtml():
'''
读取当前目录下的所有html文件,并查找本地图片,实现嵌入图片的base64编码
:return: 无
'''
for file in os.listdir('.'):
if file.endswith(".html"):
# print (file)
with open(file,'r+',encoding='utf-8') as html:
content = html.read() # 读取html文件内容
pics = findimg(content) # 查找所有内容中的本地图片
for pic in pics:
if os.path.exists(pic):
base64code = imgbase64(pic) # base64编码图片文件
content = content.replace(pic,base64code) # 替换html文件内容
content = findcomment(content) # 去除html文件中的注释
html.seek(0)
html.write(content) # 覆写
# 打包命令
# pyinstaller --noupx -F -w --icon=mylogo.ico imgbase64.py
if __name__ == '__main__':
readhtml()
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
python实现网页嵌入本地图片.7z (2个子文件)
imgbase64.exe 5.17MB
imgbase64.py 3KB
共 2 条
- 1
资源评论
onlyshi
- 粉丝: 197
- 资源: 35
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功