1. 概述
无他,这篇博文记录一下利用Python将OpenCV图片转换为base64字符串并在网页上进行展示的过程,权当备忘。可在这里查看源码。
2. Show the code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| import base64
import cv2
def img_to_base64(img_path): img = cv2.imread(img_path)
_, buffer = cv2.imencode('.jpg', img) text = base64.b64encode(buffer).decode('ascii') return text
def create_html_file(text, file_name): html_pattern = """ <html> <body> <img src="data:image/png;base64,{}"/> </body> </html> """
html = html_pattern.format(text) with open(file_name, 'w') as f: f.write(html)
if __name__ == '__main__': img_path = 'data/cat.jpg' html_file_name = 'data/show_img.html'
text = img_to_base64(img_path) create_html_file(text, html_file_name)
|