简体   繁体   中英

pygame image to base64

I capture screen of my pygame program like this

           data = pygame.image.tostring(pygame.display.get_surface(),"RGB")

How can I convert it into base64 string? (WITHOUT having to save it to HDD). Its important that there is no saving to HDD. I know I can save it to a file and then just encode the file to base64 but I cant seem to encode "on the fly"

thanks

If you want, you can save it to a StringIO , which is basically a virtual file stored as a string.

However, I'd really recommend using the base64 module, which has a method called base64.b64encode . It handles your 'on the fly' requirement well.

Code example:

import base64
data = pygame.image.tostring(pygame.display.get_surface(),"RGB")
base64data = base64.b64encode(data)

Happy coding!

Actually - pygame.image.tostring() is a pretty strange function (really dont understand the binary string it returns, I cant find anythin that can process it right).

There seems to be an enhancement issue on this at pygame bitbucket: ( https://bitbucket.org/pygame/pygame/issue/48/add-optional-format-argument-to )

I got around it like this:

            data = cStringIO.StringIO()
            pygame.image.save(pygame.display.get_surface(), data)
            data = base64.b64encode(data.getvalue())

So in the end you get the valid and RIGHT base64 string. And it seems to work. Not sure about the format yet tho, will add more info tmrw

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