How to create images on the run with PIL and Python¶
Or, how to paste 2 images into another one
I have just talked about PIL and how to create a very basic image with it from... nothing, cointaning just... 1 color. Now we are going a little further, mixing three images in one... I did something like this loading pictures of cards, but here I don't use images, I just create them with colors, nothing to load. I have a purpose on my mind, but I will explain it later.
- I want to create 3 images
- one gray
- another white for spacing between gray and red one
- the red one
Pratically, I created 3 images, one gray, one red and one white. The boxes will be the gray and the red one. The white is only for spacing. The gray one is the one in which the other two will be pasted. So the result will be an image with two boxes, gray and red, divided by a 8 pixels white space.
from IPython.core.display import display
from PIL import Image
img = Image.new("RGB",(368,120),"gray") # The gray longest one 360 + 8 for space
img2 = Image.new("RGB",(180,120),"red") # the red one half the width: 180
img3 = Image.new("1",(8,120),'white') # this is the 8 pixel wide area in the middle
img.paste(img3,(180,0)) # I paste the white space at 360
img.paste(img2,(188,0)) # I paste the red space at 368
display(img) # Here I display the result
del img # I delete the object
This code runs in jupyter notebook, but if you want to use it somewhere else, use this one:
from PIL import Image img = Image.new("RGB",(368,120),"gray") # The gray longest one 360 + 8 for space img2 = Image.new("RGB",(180,120),"red") # the red one half the width: 180 img3 = Image.new("1",(8,120),'white') # this is the 8 pixel wide area in the middle img.paste(img3,(180,0)) # I paste the white space at 360 img.paste(img2,(188,0)) # I paste the red space at 368 img.show() # This will open the default image viewer of your device del img
When you will run the code, the default image viewer will show up. Do you want to save the image in the dir where the python file with this program has been saved? Then add this code:
from PIL import Image img = Image.new("RGB",(368,120),"gray") # The gray longest one 360 + 8 for space img2 = Image.new("RGB",(180,120),"red") # the red one half the width: 180 img3 = Image.new("1",(8,120),'white') # this is the 8 pixel wide area in the middle img.paste(img3,(180,0)) # I paste the white space at 360 img.paste(img2,(188,0)) # I paste the red space at 368 img.show() # This will open the default image viewer of your device img.save("grayandred.png") del img
Se ya next time.
Comments
Post a Comment