0

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))
0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.