はじめに
HTMLファイルを配布するなんて普通の人は考えないでしょう。
Webページとして提供するべきだからです。
しかし、もしかしたらHTMLファイルを直に渡したい人がいるかもしれません。
この記事では、配布するHTMLファイルに画像を埋め込む方法を紹介します。
結論
以下のPythonスクリプトを使ってください。
HTMLファイルと画像ファイルはローカルに保存されていることが前提です。
使い方はpython script.py --help
で表示されます。
import argparse
import base64
import re
from pathlib import Path
# parse command line arguments
parser = argparse.ArgumentParser(description='Convert images in HTML into Base64')
parser.add_argument('input', type=Path, help='input HTML file path')
parser.add_argument('-o', '--output', type=Path, help='output HTML file path')
args = parser.parse_args()
input_path: Path = args.input
output_path: Path = args.output
if output_path is None:
stem = input_path.stem
output_path = input_path.with_stem(stem + '_')
parent_path = input_path.parent
# load a HTML file
with open(input_path, 'r') as f:
input_html = f.read()
# convert an image data into a data url
def path2base64(match):
img_src = match[2]
img_path: Path = parent_path / img_src
try:
with open(img_path, 'rb') as f:
img_type = img_path.suffix.strip('.')
img_data = f.read()
base64_data = base64.b64encode(img_data).decode('utf-8')
new_img_src = f"data:image/{img_type};base64,{base64_data}"
return match[1] + new_img_src + match[3]
except:
return match[0]
# replace `src` attribute value of `img` element
output_html = re.sub(r'(?ims)(<img.+?src\s*=")([^ "]+?)(".*?>)', path2base64, input_html)
# save as a new HTML file
with open(output_path, 'w') as f:
f.write(output_html)
解説
正規表現でimg要素のsrc属性を抜き出し、パスをデータURLに変換しているだけです。
おわりに
これで晴れてHTMLファイル単体で送れるようになりましたね(JSやCSSも埋め込まれている限り)。