How do I create a new image with a black background and paste another image on top of it?
What I am looking to d开发者_如何学Pythono is turn some 128x128 transparent icons into 75x75 black background icons.
Doesnt work ...
import Image theFile = "/home/xxxxxx/Pictures/xxxxxx_128.png" img = Image.open(theFile) newImage = Image.new(img.mode, img.size, "black") newImage.paste(img) newImage.resize((75,75)) newImage.save("out.png") print "Done"
Thanks!
The resize
method returns a new image object, rather than changing the existing one. Also, you should resize the image before pasting it. The following works for me:
import Image
theFile = "foo.png"
img = Image.open(theFile)
resized = img.resize((75,75))
r, g, b, alpha = resized.split()
newImage = Image.new(resized.mode, resized.size, "black")
newImage.paste(resized, mask=alpha)
newImage.save("out.png")
print "Done"
I found an example of this split
+ mask
technique from this blog post.
Example input:
Output:
精彩评论