Set transparency level using Python Imaging Library/Pillow

Image processing can be allowed using The Python Imaging Library or PIL. Unfortunately PIL’s last release was in 2009 and then it stopped getting updated. Luckily there were some Python techies who came along and forked PIL and named their project as Pillow. This project Pillow is the enhanced replacement of PIL which also supports Python 3.

Note :- You cannot have both PIL and Pillow installed at the same time.

Install pillow

pip install Pillow

Transparency level –

Transparency level determines how much transparent and opaque the pixels of an image could get. An alpha channel of an image represents its transparency.

  • When the value of alpha channel of one image is 0 and of another image is 1, only the second image will be displayed since its pixels are opaque.
  • When the value of alpha channel of one image is 1 and of another image is 0, only the first image will be displayed as the pixels of the first image are opaque.
  • When alpha channels of both the images are opaque, both the pixels are to be displayed – Transparency levels are determined by the color of the pixels from both the images equally.

code –

from PIL import Image

def changeImageSize(maxWidth, maxHeight, image):

    widthRatio  = maxWidth/image.size[0]
    heightRatio = maxHeight/image.size[1]

    newWidth    = int(widthRatio*image.size[0])
    newHeight   = int(heightRatio*image.size[1])

    newImage    = image.resize((newWidth, newHeight))
    return newImage

image1 = Image.open("./Space.png")     #path of first image
image2 = Image.open("./Universe.png")     #path of second image

image1 = changeImageSize(3290, 1300, image1)
image2 = changeImageSize(3290, 1300, image2)

alphaBlended = Image.blend(image1, image2, alpha=.3)
alphaBlended.show()

output –

Image 1
Image 2
At alpha 0.3
At alpha 0.6

Conclusion –

As you can see, it is pretty easy and simple to use this library for adjusting the transparency at multiple levels. This library is widely used out there in the wild, make sure you master it.

Ayush

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s