Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use PIL (Python Image Library) rotate image and let black background to be transparency

I want to rotate a gray "test" image and paste it onto a blue background image. Now I just can remove the black color after rotate my gray "test" image, but their is now a white color section. How can I use Python to change the "white" color section to blue?

Here is my code, can someone help me? I'd appreciate it.

dst_im = Image.new("RGBA", (196,283), "blue" )
im = src_im.convert('RGBA')
rot = im.rotate( angle, expand=1 ).resize(size)
f = Image.new( 'RGBA', rot.size, (255,)*4 )
im2 = Image.composite( rot, f, rot )
im2.convert(src_im.mode)
im2_width, im2_height = im2.size
cut_box = (0, 0, im2_width, im2_height )
paste_box = ( left, top, im2_width+left, im2_height+top )
region = im2.crop( cut_box )
dst_im.paste( region, paste_box )
dst_im.save("test.gif")

enter image description here

like image 937
Apple Wang Avatar asked Aug 13 '12 15:08

Apple Wang


1 Answers

I have the impression that your code could be simplified as follows:

from PIL import Image

src_im = Image.open("winter3.jpg")
angle = 45
size = 100, 100

dst_im = Image.new("RGBA", (196,283), "blue" )
im = src_im.convert('RGBA')
rot = im.rotate( angle, expand=1 ).resize(size)
dst_im.paste( rot, (50, 50), rot )
dst_im.save("test.png")

This gives the following result:

enter image description here

like image 135
user1202136 Avatar answered Sep 20 '22 09:09

user1202136