使用 Pillow 将 png 转换为 jpeg

我试图转换 png 到 jpeg 使用枕头。我试了好几种处方都没有成功。这两个似乎工作在像这样的小 png 图像上。

enter image description here

第一个代码:

from PIL import Image
import os, sys


im = Image.open("Ba_b_do8mag_c6_big.png")
bg = Image.new("RGB", im.size, (255,255,255))
bg.paste(im,im)
bg.save("colors.jpg")

第二守则:

image = Image.open('Ba_b_do8mag_c6_big.png')
bg = Image.new('RGBA',image.size,(255,255,255))
bg.paste(image,(0,0),image)
bg.save("test.jpg", quality=95)

但是如果我试图转换一个像这样的大图像

我得到了

Traceback (most recent call last):
File "png_converter.py", line 14, in <module>
bg.paste(image,(0,0),image)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1328, in paste
self.im.paste(im, box, mask.im) ValueError: bad transparency mask

我做错了什么?

133736 次浏览

You can convert the opened image as RGB and then you can save it in any format. The code will be:

from PIL import Image
im = Image.open("image_path")
im.convert('RGB').save("image_name.jpg","JPEG") #this converts png image as jpeg

If you want custom size of the image just resize the image while opening like this:

im = Image.open("image_path").resize(x,y)

and then convert to RGB and save it.

The problem with your code is that you are pasting the png into an RGB block and saving it as jpeg by hard coding. you are not actually converting a png to jpeg.

You should use convert() method:

from PIL import Image


im = Image.open("Ba_b_do8mag_c6_big.png")
rgb_im = im.convert('RGB')
rgb_im.save('colors.jpg')

more info: http://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.convert

The issue with that image isn't that it's large, it is that it isn't RGB, specifically that it's an index image. enter image description here

Here's how I converted it using the shell:

>>> from PIL import Image
>>> im = Image.open("Ba_b_do8mag_c6_big.png")
>>> im.mode
'P'
>>> im = im.convert('RGB')
>>> im.mode
'RGB'
>>> im.save('im_as_jpg.jpg', quality=95)

So add a check for the mode of the image in your code:

if not im.mode == 'RGB':
im = im.convert('RGB')

if you want to convert along with resize then try this,

from PIL import Image


img = i.open('3-D Tic-Tac-Toe (USA).png').resize((400,400)) # (x,y) pixels
img.convert("RGB").save('myimg.jpg')

thats it.. your resized and converted image will store in same location