Dom
Dom

Reputation: 43

Convert multiple base64 to Images in Python

I am trying to convert a list of strings to byte64 format so I can decode them and download them as Images. The byte64 format images are stored in file.txt and a snippet of the file is shown below. My attempt only does this for a single byte64 format string, how should I do this for a file containing multiple lines?

snippet from file.txt:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/...
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/...

Here's what I've tried to do:

# read lines from file
f = open("file.txt", "r")
for x in f:
  data = f.readlines()
f.close()


# Removing unecessary substrings
images = [w.replace('\n', '') for w in data]
images = [w.replace('data:image/jpeg;base64,', '') for w in images]


# encode string to byte64 format
test = images[1].encode()

# Convert to image
with open("image_1.png", "wb") as fh:
    fh.write(base64.decodebytes(test))

Upvotes: 0

Views: 995

Answers (1)

dwb
dwb

Reputation: 2624

If all of your code is working, then it should be as simple as changing the index and file name.

data = []
with open("file.txt", "r") as f
  # for x in f:      i dont know why this was in a loop
  data = f.readlines()

# do this in one line
images = [w.replace('\n', '').replace('data:image/jpeg;base64,', '') for w in data]


for index, base64string in enumerate(images):

  test = base64string.encode()

  with open("image_{0}.png".format(index), "wb") as fh:
    fh.write(base64.decodebytes(test))

I haven't run this code, but it looks like it should work to me.

Upvotes: 1

Related Questions