0

I have the following program:

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:] + '===='))

Intent is to pick base64 data from a file and create jpeg files from it. But somehow it is not identifying the starting characters as jpeg (have tried using jpg) and is skipping the data.

enter image description here

jps
  • 20,041
  • 15
  • 75
  • 79
etrnllrnr
  • 1
  • 3
  • 2
    Does this answer your question? [Convert string in base64 to image and save on filesystem in Python](https://stackoverflow.com/questions/2323128/convert-string-in-base64-to-image-and-save-on-filesystem-in-python) – Vishnudev Krishnadas Feb 22 '21 at 08:27
  • on your screenshot I see it starts with /9j/, that`s a base64 encoded jpeg header. So you can directly base64 decode the file, there is no 'data:image/jpeg;base64,' data-url prefix. – jps Feb 22 '21 at 09:10

1 Answers1

0

Thanks @jps and @vishnudev. It works fine with the following changes.

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))
etrnllrnr
  • 1
  • 3