Make PNG sprites in PIL but want to preserve alpha channel
I'm creating a script to grab a bunch of favicons, convert them to png and make a single sprite image out of all of them.
The helpful g.etfv.co will detect and convert favicons in PNG format, and I'm using PIL to montage the images into a sprite sheet.
It all works fine except I seem to lose the alpha transparency channel when I do this.
Resulting image from the below script:
Update: Now creating image in mode 'RGBA' rather than 'RGB'. Resulting image is 开发者_Python百科now only partially borked:
. OKCupid's icon looks correct but stackoverflow's is still losing the alpha channel.Update: I note that it so happens that images it messes up on it reports as being RGB (not RGBA) prior to conversion.
>>> print url, img.getbands()
http://stackoverflow.com/ ('R', 'G', 'B')
http://www.google.com/ ('R', 'G', 'B')
http://blog.okcupid.com/ ('R', 'G', 'B', 'A')
What am I doing wrong?
import urllib
import PIL.Image
import StringIO
favicon_base = 'http://g.etfv.co/'
icons = """
http://stackoverflow.com/
http://www.google.com/
http://blog.okcupid.com/
"""
icons = [icon.strip() for icon in icons.strip().splitlines()]
left = 0
right = 16
upper = 0
lower = 16
inew = PIL.Image.new('RGBA',(len(icons)*16,16))
for url in icons:
favicon = urllib.urlopen(favicon_base + urllib.quote(url) + '?defaulticon=lightpng').read()
img = PIL.Image.open(StringIO.StringIO(favicon))
img = img.convert('RGBA')
bbox = (left, upper, right, lower)
inew.paste(img, bbox, img)
left += 16
right += 16
inew.save(open('blah.png', 'wb'), 'png', optimize=1)
The result image inew
has no alpha chanel.
UPDATE:
try
inew = PIL.Image.new('RGBA',(len(icons)*16,16))
精彩评论