Reg*_*ing 17 python image-processing python-imaging-library
我正在使用PIL1.1.7在Python 2.7中对图像处理器进行原型设计,我希望所有图像都以JPG结尾.输入文件类型将包括透明和没有的tiff,gif,png.我一直在尝试组合两个脚本,我发现1.将其他文件类型转换为JPG和2.通过创建空白图像并将原始图像粘贴到白色背景上来消除透明度.我的搜索是垃圾邮件,人们试图产生或保持透明度,而不是相反.
我正在使用这个:
#!/usr/bin/python
import os, glob
import Image
images = glob.glob("*.png")+glob.glob("*.gif")
for infile in images:
f, e = os.path.splitext(infile)
outfile = f + ".jpg"
if infile != outfile:
#try:
im = Image.open(infile)
# Create a new image with a solid color
background = Image.new('RGBA', im.size, (255, 255, 255))
# Paste the image on top of the background
background.paste(im, im)
#I suspect that the problem is the line below
im = background.convert('RGB').convert('P', palette=Image.ADAPTIVE)
im.save(outfile)
#except IOError:
# print "cannot convert", infile
Run Code Online (Sandbox Code Playgroud)
这两个脚本都是孤立的,但是当我将它们组合起来时,我得到一个ValueError:Bad Transparency Mask.
Traceback (most recent call last):
File "pilhello.py", line 17, in <module>
background.paste(im, im)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1101, in paste
self.im.paste(im, box, mask.im)
ValueError: bad transparency mask
Run Code Online (Sandbox Code Playgroud)
我怀疑如果我要保存一个没有透明度的PNG,我可以打开那个新文件,然后重新保存为JPG,并删除写入磁盘的PNG,但我希望有一个优雅的解决方案我还没有找到.
kin*_*all 30
制作背景RGB,而不是RGBA.当然,删除后面的背景转换为RGB,因为它已经处于该模式.这对我来说对我有一个我创建的测试图像:
from PIL import Image
im = Image.open(r"C:\jk.png")
bg = Image.new("RGB", im.size, (255,255,255))
bg.paste(im,im)
bg.save(r"C:\jk2.jpg")
Run Code Online (Sandbox Code Playgroud)
小智 7
image=Image.open('file.png')
non_transparent=Image.new('RGBA',image.size,(255,255,255,255))
non_transparent.paste(image,(0,0),image)
Run Code Online (Sandbox Code Playgroud)
关键是使掩模(用于粘贴)图像本身.
这应该适用于那些具有"软边缘"的图像(其中alpha透明度设置为0或255)
以下对我来说适用于这张图片
f, e = os.path.splitext(infile)
print infile
outfile = f + ".jpg"
if infile != outfile:
im = Image.open(infile)
im.convert('RGB').save(outfile, 'JPEG')
Run Code Online (Sandbox Code Playgroud)