简体   繁体   English

为什么在PIL.Image上调整大小/缩略图不起作用? 蟒蛇

[英]Reason why resize/thumbnail on PIL.Image doesn't work? Python

I am trying to resize a PNG image. 我正在尝试调整PNG图片的大小。 Worth noting that before the image becomes PNG it is converted from SVG (working without problems). 值得注意的是,在图像变为PNG之前,它已从SVG转换(正常工作)。

This is the code: 这是代码:

        if format == 'png':
            output = BytesIO()
            svg2png(bytestring=monkey_image.to_str(), write_to=output)
            contents = output.getvalue()
            size = 15, 15
            img = Image.open(BytesIO(contents))
         #  tried both resize and thumbnail, same result
         #  img.thumbnail(size, Image.ANTIALIAS) 
            img = img.resize(size, Image.ANTIALIAS)
            img.save(output, format="PNG")
            contents = output.getvalue()
            output.close()
        return contents

The result I am seeing is that it returns the image in the original size (retures the first defined contents) 我看到的结果是它返回了原始大小的图像(显示了第一个定义的内容)

Maybe I am not saving it correctly to the output in the second to? 也许我第二次没有正确地将其保存到输出中?

You are appending your data to an existing BytesIO object. 您正在将数据追加到现有的BytesIO对象。 Additional writes to such an object do not replace existing data; 对此类对象的其他写入操作不会替换现有数据。 writing adds more data to the end of the file: 写入会将更多数据添加到文件末尾:

>>> from io import BytesIO
>>> out = BytesIO()
>>> out.write(b'123')
3
>>> out.getvalue()
b'123'
>>> out.write(b'456')
3
>>> out.getvalue()
b'123456'

You now have binary data for two images in a single file, but compliant decoders will ignore trailing data in an image file. 现在,您在单个文件中具有两个图像的二进制数据,但是兼容的解码器将忽略图像文件中的尾随数据。

Use a new, empty BytesIO() object: 使用一个新的空 BytesIO()对象:

resized = BytesIO()
img.save(resized, format="PNG")
contents = resized.getvalue()

You could also seek to the start of the file and truncate: 您也可以寻找文件的开头并截断:

output.seek(0)
output.truncate()

before writing to it again, but just creating a new in-memory file object is clearer and less error-prone. 在再次写入之前,但是仅创建一个新的内存文件对象更加清晰,并且不容易出错。

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

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