Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在PYTHON中将Base64字符串转换为图像_Python_Image_Web Scraping_Base64 - Fatal编程技术网

如何在PYTHON中将Base64字符串转换为图像

如何在PYTHON中将Base64字符串转换为图像,python,image,web-scraping,base64,Python,Image,Web Scraping,Base64,我正在抓取亚马逊产品的图片,但过了一段时间我得到的是base64字符串而不是图片链接,所以我想把这个字符串转换成图片 我尝试了这个代码,但出现了错误 代码: import base64 from PIL import Image from io import BytesIO f = open('C:\\Users\\pc\\Desktop\\base64.txt','r') data = f.read() im = Image.open(BytesIO(base64.b64decode(dat

我正在抓取亚马逊产品的图片,但过了一段时间我得到的是base64字符串而不是图片链接,所以我想把这个字符串转换成图片

我尝试了这个代码,但出现了错误

代码:

import base64
from PIL import Image
from io import BytesIO

f = open('C:\\Users\\pc\\Desktop\\base64.txt','r')
data = f.read()
im = Image.open(BytesIO(base64.b64decode(data)))
im.save('C:\\Users\\pc\\Desktop\\image.png', 'PNG')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\pc\AppData\Local\Programs\Python\Python39\lib\base64.py", line 87, in b64decode
    return binascii.a2b_base64(s)
binascii.Error: Invalid base64-encoded string: number of data characters (16369) cannot be 1 more than a multiple of 4
错误:

import base64
from PIL import Image
from io import BytesIO

f = open('C:\\Users\\pc\\Desktop\\base64.txt','r')
data = f.read()
im = Image.open(BytesIO(base64.b64decode(data)))
im.save('C:\\Users\\pc\\Desktop\\image.png', 'PNG')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\pc\AppData\Local\Programs\Python\Python39\lib\base64.py", line 87, in b64decode
    return binascii.a2b_base64(s)
binascii.Error: Invalid base64-encoded string: number of data characters (16369) cannot be 1 more than a multiple of 4

我知道有很多这样的问题,但我没有找到好的答案

此数据不完全是
base64
请注意前缀数据:

data:image/webp;base64,
必须首先剥离此数据,然后将其作为图像处理为有效的
base64

import base64
from PIL import Image
from io import BytesIO

f = open('C:\\Users\\pc\\Desktop\\base64.txt','r')
data = f.read()
prefix = 'data:image/webp;base64,'
cut = data[len(prefix):]
im = Image.open(BytesIO(base64.b64decode(cut)))
im.save('C:\\Users\\pc\\Desktop\\image.png', 'PNG')

只需删除包括逗号在内的第一个字符
UklGR..
是您的base64字符串