python将图片文件转换成base64编码,方便网页调用

2022-05-03 00:00:00 调用 编码 文件转换成

在网页里调用图片除了可以直接给定图片路径外,还可以使用base64编码,下面的python代码可以将图片转换成base64编码

"""
作者:皮蛋编程(https://www.pidancode.com)
创建日期:2022/3/26
功能描述:python将图片文件转换成base64编码,方便网页调用
"""
import base64

f = open('pidancode.png', 'rb')  # 二进制方式打开图文件
ls_f = base64.b64encode(f.read())  # 读取文件内容,转换为base64编码
f.close()
print(ls_f)

调用方法

<img 
src="data:image/bmp;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAABBCAYAAABW168KAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAOwwAADsMBx2+oZAAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNui8sowAAAAWdEVYdENyZWF0aW9uIFRpbWUAMDgvMTQvMTn/954FAAAXV0lEQVR4nO2deZRcRfXHP9Uzk8meAAkgyCoQgUOEIIkgIIqyKIRD0hdBFkEB+flzQxTcEMFzFEEWFUUJ/ERBIrlNRMWf+JN9CWAQFBAhYckRBFmyQEIyyUx3/f64VdOvX153v+lMMnjs7zl9uru6Xr37qm7dultVO+89bbQxVCgMNQFt/GejzYBtDCnaDNjGkKLNgG0MKdoM2MaQos2AbQwp2gzYxpCizYBtDCk6h5qAvBCRk4CDgFWAB9wgNu+AS1X1r4PYZkMUi8V9ga5SqXT7hrrnmxFDxoAiAiaBCxgDdAJ9qtpb55L9gKPXFz3e++uB9c6AIrIjcLRz7jRggYjcrap96/u+b1ZsEAYUkc2ArwNbAn1AR+LVGd7HAjcC39oQNGVgTfwgIp0Ag80YIjIeuAaYFoq2AI4EdDDv8++EDSUBxwPHABs1qfdUg99GDB45mUgGxWcC5xaLxdnOuTuAh1X19ayLgiQfHq4vAxWgoro2T6nqMhEpAVOArlD8FdoMODCISDewFzAGWA30YpItvq/BOvg5VV0CLAOW0JwBX27w2yxgAfA6tmRHHbAH+AjwriZtLwO+D7yIMcwpwC516h4ETHLOf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