pyinstaller 打包图片后 怎么读取
时间: 2023-07-09 17:13:39 浏览: 68
如果你使用 PyInstaller 打包了一个包含图片的 Python 应用程序,并且想要在程序中读取这些图片,你可以使用以下方法:
1. 使用相对路径读取图片
在代码中使用相对路径来读取图片,如下所示:
```python
import os
import sys
# 获取当前脚本文件所在目录
current_path = sys._MEIPASS if hasattr(sys, '_MEIPASS') else os.path.abspath('.')
# 拼接图片路径
image_path = os.path.join(current_path, 'images', 'example.png')
# 读取图片
with open(image_path, 'rb') as f:
image_data = f.read()
```
这里,`sys._MEIPASS` 是 PyInstaller 为我们提供的一个变量,表示打包后的程序所在目录,如果这个变量不存在,则说明程序没有被 PyInstaller 打包,使用 `os.path.abspath('.')` 获取当前脚本文件所在目录。
2. 将图片嵌入代码中
使用 Python 的 `base64` 模块将图片嵌入代码中,如下所示:
```python
import base64
# 读取图片文件
with open('example.png', 'rb') as f:
image_data = f.read()
# 将图片转换为 Base64 编码
image_base64 = base64.b64encode(image_data).decode('utf-8')
# 在 HTML 中使用 Base64 编码的图片
html = f'<img src="data:image/png;base64,{image_base64}">'
```
这里,`base64.b64encode` 将图片数据编码为 Base64,`decode('utf-8')` 将字节数据转换为字符串。在 HTML 中使用 Base64 编码的图片时,需要指定图片格式和编码方式,如上例中的 `data:image/png;base64,` 表示图片格式为 PNG,编码方式为 Base64。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)