Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.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_Base64_Python Imaging Library - Fatal编程技术网

Python 不同base64的枕头编码和解码结果

Python 不同base64的枕头编码和解码结果,python,base64,python-imaging-library,Python,Base64,Python Imaging Library,我正在尝试从base64转换为PIL图像,并将PIL图像转换为base64。我正在使用这些脚本 def convert_base64_2_pil_image(image_b64: bytes) -> Image: image_str = base64.b64decode(image_b64) return Image.open(io.BytesIO(image_str)) def convert_pil_image_2_base64(image: Image, form

我正在尝试从base64转换为PIL图像,并将PIL图像转换为base64。我正在使用这些脚本

def convert_base64_2_pil_image(image_b64: bytes) -> Image:
    image_str = base64.b64decode(image_b64)
    return Image.open(io.BytesIO(image_str))


def convert_pil_image_2_base64(image: Image, format: str = 'PNG') -> bytes:
    buffered = io.BytesIO()
    image.save(buffered, format=format)
    buffered.seek(0)
    return base64.b64encode(buffered.getvalue())
当我尝试将一个base64字符串转换为PIL映像,然后再次将该PIL映像转换为base64时,base64字符串是不同的。我丢失了一些信息

image_b64 = b'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=='
image = convert_base64_2_pil_image(image_b64)
image_b64_converted = convert_pil_image_2_base64(image)
assert image_b64_converted == image_b64

如何解决此问题?

您的base-64字符串不同并不一定意味着您丢失了信息。如果您想获得更好的分析/回答,您需要以精确的原始形式提供图像和base-64表示法-可能通过DropboxGoogle Drive-因为大多数网站都会将影响base-64表示法的地理信息和其他信息剥离出来

因此,回到您的问题,对于base-64表示形式可能不同的原因,有几种可能的解释:

  • 首先,PNG图像通常包含上一次更改的日期/时间作为辅助块,因此仅在1秒后打开并重新保存纯黑色图像可能会更改base-64表示

  • 其次,虽然是无损的,但不能保证两个库在位深度、调色板、alpha、过滤等方面做出相同的决定。例如,一个库可以选择将具有有限数量颜色的图像保存为调色板图像,而另一个库可以选择RGB表示,另一个库可以选择RGBA表示。看见一个可以选择每个样本8位的PNG,另一个可以选择每个样本16位的PNG