开发者

Python Image Library - Create and paste image

开发者 https://www.devze.com 2023-02-17 18:21 出处:网络
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

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:

Python Image Library - Create and paste image

Output:

Python Image Library - Create and paste image

0

精彩评论

暂无评论...
验证码 换一张
取 消