简体   繁体   中英

Python Base64 encoding of an image not working

I have generated a base64 string from an image in Python (need the string to write in an XML file).

with open(f"./images/sample.png", "rb") as img:
        encoded_string = base64.b64encode(img.read())
return str(encoded_string)

The encoded string is very different from what is returned from an online image to base64 converter tool (Let's call this image_string ). Also the encoded_string is not working as expected with my XML file and the string from the conversion tool works well.

For a very simple red dot image, the image_string is iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAM1BMVEX/////QAAAAAD39/fd3d1cZWb09PT/RADXNQCZGwAADRPwOgCdnp/pOQDmOACcHACmp6gpMfrfAAAApUlEQVR4nO3WCw6CMBAFQFgo0KLi/U+rRo5gbVJmTvA2m/0MAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAvzItU+sIVc2pRElz6xj13OLY1z3Hs3WQWubYxo8teu1iyuNXTq2j1DGV+1nho/S5bpZYzwrXWFqHqaL/HvY/hxfYpe97mPu+hxf4aYb+/1IAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP96AYz9AjI6JdQCAAAAAElFTkSuQmCC while the encoded_string is long with padding.

Can someone shed some light on why the python generated string maybe very long and how I can convert it back to a string without padding?

I'd be very surprised if the encoded_string was not very large for any reasonably-sized image. Can you give some more detail as to how you're putting it into the XML? A link to the image would be very helpful as well.

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.

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