I want to convert some base64 encoded png images to jpg using python. I know how to decode from base64 back to raw:
import base64
pngraw = base64.decodestring(png_b64text)
but how can I convert this now to jpg? Just writing pngraw to a file obviously only gives me a png file. I know I can use PIL, but HOW exactly would I do it? Thanks!
You can use PIL:
data = b'''iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAAXNSR0IArs4c6QAAAIBJRE
FUOMvN08ENgCAMheG/TGniEo7iEiZuqTeiUkoLHORK++Ul8ODPZ92XS2ZiADITmwI+sWHwi
w2BGtYN1jCAZF1GMYDkGfJix3ZK8g57sJywteTFClBbjmAq+ESiGIBEX9nCqgl7sfyxIykt
7NUUD9rCiupZqAdTu6yhXgzgBtNFSXQ1+FPTAAAAAElFTkSuQmCC'''
import base64
from PIL import Image
from io import BytesIO
im = Image.open(BytesIO(base64.b64decode(data)))
im.save('accept.jpg', 'JPEG')
In very old Python versions (2.5 and older), replace b'''
with '''
and from io import BytesIO
with from StringIO import StringIO
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With