1

How do I create a new image with a black background and paste another image on top of it?

What I am looking to do 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!

1 Answer 1

10

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:

Input image

Output:

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

I get a resized image of the original PNG with transparency.
Sorry, I checked the results in a program that it seems uses a black background for transparent images anyway :) I've updated my answer with a fixed version, tested properly this time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.