简体   繁体   English

python:将base64编码的png图像转换为jpg

[英]python: convert base64 encoded png image to jpg

I want to convert some base64 encoded png images to jpg using python. 我想使用python将一些base64编码的png图像转换为jpg。 I know how to decode from base64 back to raw: 我知道如何从base64解码回原始:

import base64 
pngraw = base64.decodestring(png_b64text)

but how can I convert this now to jpg? 但是我现在如何将其转换为jpg? Just writing pngraw to a file obviously only gives me a png file. 只是将pngraw写入文件显然只给我一个png文件。 I know I can use PIL, but HOW exactly would I do it? 我知道我可以使用PIL,但我该如何做呢? Thanks! 谢谢!

You can use PIL : 你可以使用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 . 在非常旧的Python版本(2.5及更早版本)中,将b'''替换为'''from io import BytesIO替换from StringIO import StringIO

Right from the PIL tutorial: 从PIL教程开始:

To save a file, use the save method of the Image class. 要保存文件,请使用Image类的save方法。 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 将文件转换为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. 所以你要做的就是将文件扩展名设置为.jpeg.jpg ,它会自动转换图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM