python: convert base64 encoded png image to jpg

前端 未结 2 1261
我在风中等你
我在风中等你 2021-02-14 20:30

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(p         


        
相关标签:
2条回答
  • 2021-02-14 21:04

    Right from the PIL tutorial:

    To save a file, use the save method of the Image class. When saving files, the name becomes important. Unless you specify the format, the library uses the filename extension to discover 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 convert the image automatically.

    0 讨论(0)
  • 2021-02-14 21:20

    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.

    0 讨论(0)
提交回复
热议问题