python怎么将字符串转为base64
时间: 2024-06-09 17:09:25 浏览: 17
Python有一个内置模块`base64`可以用来进行Base64编码和解码。下面是一个示例:
```python
import base64
# 将字符串编码为Base64
str = 'Hello, world!'
encoded_str = base64.b64encode(str.encode('utf-8'))
print(encoded_str) # b'SGVsbG8sIHdvcmxkIQ=='
# 将Base64编码解码为字符串
decoded_str = base64.b64decode(encoded_str).decode('utf-8')
print(decoded_str) # 'Hello, world!'
```
在上面的示例中,我们首先将字符串`'Hello, world!'`编码为Base64格式,然后将其打印出来。接着,我们将这个Base64编码解码为字符串,并将其打印出来。
相关问题
python将base64字符串转换为mp4
可以使用base64模块和ffmpeg库来实现将base64字符串转换为mp4视频文件,具体实现如下:
```python
import base64
import subprocess
# 读取base64字符串
with open("video.txt", "r") as f:
base64_str = f.read()
# 将base64字符串解码为二进制数据
video_data = base64.b64decode(base64_str)
# 将二进制数据写入临时文件
with open("video.mp4", "wb") as f:
f.write(video_data)
# 使用ffmpeg将临时文件转换为mp4视频文件
subprocess.run(["ffmpeg", "-i", "video.mp4", "-codec", "copy", "output.mp4"])
```
在上述代码中,我们先读取了一个名为video.txt的文件,该文件中存储了我们需要转换的base64字符串。然后使用base64模块将该字符串解码为二进制数据,并将其写入临时文件video.mp4中。最后,我们使用ffmpeg库将临时文件video.mp4转换为mp4视频文件output.mp4。注意,我们在命令行中使用了-codec copy参数,表示直接将视频流从原始文件复制到输出文件中,以避免重新编码导致的质量损失和性能问题。
python 将 base64 编码的字符串转换为图片
可以使用 Python 的 base64 模块来解码 base64 编码的字符串,然后将其写入文件中,从而生成图片。以下是一个示例代码:
```python
import base64
# 读取 base64 编码的字符串
with open('image.txt', 'r') as f:
image_data = f.read()
# 解码 base64 字符串
image_binary = base64.b64decode(image_data)
# 将二进制数据写入图片文件
with open('image.jpg', 'wb') as f:
f.write(image_binary)
```
在上面的代码中,我们首先从文件中读取 base64 编码的字符串,然后使用 `base64.b64decode()` 方法将其解码为二进制数据。最后,我们将二进制数据写入一个新的图片文件中。注意,图片格式需要与原来的图片格式一致。