Python: convert base64 PNG image to jpg

I want to convert 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 gives me only a png file. I know I can use PIL, but HOW would I do it? Thanks!

+8
python image png jpeg
source share
2 answers

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 versions of Python (2.5 and older), replace b''' with ''' and from io import BytesIO with from StringIO import StringIO .

+19
source share

To the right of the PIL tutorial:

To save the file, use the save method of the Image class. When saving files, the name becomes important. If you do not specify a format, the library uses the file name extension to determine which file storage format to use.

Convert files to JPEG

 import os, sys import Image for infile in sys.argv[1:]: f, e = os.path.splitext(infile) outfile = f + ".jpg" if infile != outfile: try: Image.open(infile).save(outfile) except IOError: print "cannot convert", infile 

So all you have to do is set the file extension to .jpeg or .jpg , and it will automatically convert the image.

+5
source share

All Articles