[SOLVED] How would you crop a PNG stored as a byte-string? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 20

[SOLVED] How would you crop a PNG stored as a byte-string?

I have a Python question for anyone who is familiar with the imgkit-module. Note the following example ... html_str = '<html><body>Hello World!</body></html>' imgkit.from_string(html_str, 'example.png') ... After running the code above, you would have a PNG named 'example.png' of what the HTML code would look like if you would have saved it as an html-file and opened it. Essentially, what imgkit does is screenshot things. A couple of other methods, besides 'from_string', would be 'from_url' and 'from_file' ... There's another way to implement this tool, and this is where my question is introduced ... img = imgkit.from_string(html_str, False) ^ The above code would have the image NOT saved to your harddisk, and instead assigns the image as a bytestring to 'img'. My question is ... "How might you resize the image while it's stored in a bytestring, without saving it to anything (creating/manipulating it in-memory only)?" I know PIL's Image module has resize methods, etc, but how in the world would you accomplish this on an image stored as a bytestring?

14th Jul 2018, 7:19 AM
Fox
Fox - avatar
4 Answers
+ 13
Have you tried using BytesIO? Example: import imgkit, io.BytesIO, PIL.Image img= imgkit.from_string(html_str,False) str_file= io.BytesIO(img) pimg= PIL.Image.open(str_file) pimg.resize((30,30)) I never used imgkit and i dont know what return .from_string (string? bytes?) but i think that this place you in right direction
14th Jul 2018, 7:46 AM
KrOW
KrOW - avatar
+ 12
These 2 methods are pretty good. By the way PIL has a lot of other functions, so if you need to draw on images for example, you could use the PIL approach, else use Kuba's method and use what you need.
14th Jul 2018, 8:01 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 11
CipherFox You can decode it to bytes using the binascii module: from binascii import unhexlify data_in_bytes = unhexlify(data_in_bytestring) and then use PIL Image's open and resize methods on it.
14th Jul 2018, 7:51 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 9
These two will help you try out PIL has a lot of other functions, so if you need to draw on images for example, you could use the PIL approach, else use Kuba's method and use what you need.
14th Jul 2018, 10:12 AM
Malkiat Singh
Malkiat Singh - avatar