I have a load of images that are currently encoded in base64. I am trying to decode them all in one go and print the output to individual files.
I am trying the code below, which results in no errors but, rather than outputting a different image for each string in the list, it outputs multiple files of the same image.
import base64
from PIL import Image
from io import BytesIO
# images = ['List of base64 strings']
for i in range(len(images)):
for b64_string in images:
im = Image.open(BytesIO(base64.b64decode(b64_string)))
im.save(f"{i}.png",'PNG')
I am new to python / programming in general so I may be well off with what I am trying, but I am keen to learn where I am going wrong. Thanks in advance :)
There is an easier way to get index values in python, you can use enumerate
. It will give you the index of the element and the element, so you can just iterate into it and do it as you wish.
for i, b64_string in enumerate(images):
im = Image.open(BytesIO(base64.b64decode(b64_string)))
im.save(f"{i}.png",'PNG')
Link to documentation: enumerate
Example from documentation:
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
Remove the inner loop, because right now you're processing each image multiple times.
for i, image in enumerate(images):
im = Image.open(BytesIO(base64.b64decode(image)))
im.save(f"{i}.png",'PNG')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.