简体   繁体   English

将多个 base64 转换为 Python 中的图像

[英]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.我正在尝试将字符串列表转换为 byte64 格式,以便将它们解码并下载为图像。 The byte64 format images are stored in file.txt and a snippet of the file is shown below. byte64 格式的图像存储在 file.txt 中,文件片段如下所示。 My attempt only does this for a single byte64 format string, how should I do this for a file containing multiple lines?我的尝试仅针对单个 byte64 格式字符串执行此操作,我应该如何针对包含多行的文件执行此操作?

snippet from file.txt:来自 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))

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.我还没有运行这段代码,但它看起来应该对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM