在 Python 中将 base64 转换为 JPEG

时间:2021-02-22 08:24:43

标签: python base64 jpeg

我有以下程序:

import fileinput
import base64

for index, line in enumerate(fileinput.input('input1.txt'), 1):
  if line.startswith('data:image/jpeg;base64,'):
    with open('image{0:04}.jpeg'.format(index), 'wb') as jpeg:
       line = line.strip()
       jpeg.write(base64.b64decode(line[22:] + '===='))

意图是从文件中选取 base64 数据并从中创建 jpeg 文件。但不知何故,它没有将起始字符识别为 jpeg(已尝试使用 jpg)并且正在跳过数据。

enter image description here

1 个答案:

答案 0 :(得分:0)

感谢@jps 和@vishnudev。它适用于以下更改。

for index, line in enumerate(fileinput.input('input1.txt'), 1):
    with open('image{0:02}.jpg'.format(index), 'wb') as jpg:
       line = line.strip()
       jpg.write(base64.b64decode(line))