base64 图片在线解码/编码
时间: 2023-10-17 10:12:53 浏览: 39
可以使用Python中的base64库进行图片的编码和解码。
以下是一个示例代码,可以将一张图片进行base64编码,并将编码后的结果进行解码并保存为新的图片文件:
```
import base64
# 将图片编码为base64格式
with open("image.png", "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
# 将base64编码的字符串解码为图片并保存
with open("decoded_image.png", "wb") as output_file:
output_file.write(base64.b64decode(encoded_string))
```
在上述代码中,首先使用`open()`函数打开要编码的图片文件,然后使用`base64.b64encode()`函数将图片内容编码为base64格式。编码后的字符串需要使用`decode()`函数转换为普通的字符串,以便后续处理。
接下来,在第二个代码块中,我们将编码后的字符串解码为原始的图片内容,并使用`open()`函数将其保存为新的图片文件。在这里,我们使用`wb`模式打开输出文件,以便正确地写入二进制数据。
如果要进行base64解码而不是编码,则可以使用`base64.b64decode()`函数对编码后的字符串进行解码。例如:
```
import base64
# 从 base64 编码的字符串中解码出图片内容
with open("base64_encoded_image.txt", "r") as encoded_file:
encoded_string = encoded_file.read()
decoded_image = base64.b64decode(encoded_string)
# 将解码后的图片内容保存为文件
with open("decoded_image.png", "wb") as output_file:
output_file.write(decoded_image)
```
在上述代码中,我们首先打开包含base64编码字符串的文件,并使用`read()`函数读取编码后的字符串。然后,我们使用`base64.b64decode()`函数将字符串解码为原始的二进制数据,并将其保存到`decoded_image`变量中。最后,我们使用`open()`函数将解码后的二进制数据写入到新的图片文件中。