Stepan Loginov
Stepan Loginov

Reputation: 1767

PNG image that support scaling and changing transparency in python

I want to show PNG picture on canvas. Before it I need to resize it and change transparency.

I found that I can load image and change alpha channel with PhotoImage like this:

image1 = PIL.Image.open('aqua.png')
image1.putalpha(128)
gif1 = ImageTk.PhotoImage(image1)

Also I can load PhotoImage and resize it like this:

gif1 = PhotoImage(file = 'aqua.png')
gif1 = gif1.subsample(5)

But I can't perform both this things on same PhotoImage

I understand that PhotoImage and ImageTk.PhotoImage are different classes in my code.

>> print (ImageTk.PhotoImage)
<class 'PIL.ImageTk.PhotoImage'>
>> print (PhotoImage)
<class 'tkinter.PhotoImage'>

I tried to found functionality that I need in both classes but without success.

Maybe I need perform subsample and than convert my tkinter.PhotoImage to PIL.ImageTk.PhotoImage and then perform putalpha but it sounds weird.

Please refer me to right direction about png cooking in Python.

Here is all my code:

from tkinter import *
import PIL
from PIL import Image, ImageTk

canvas = Canvas(width = 200, height = 200)
canvas.pack(expand = YES, fill = BOTH)

image1 = PIL.Image.open('aqua.png')
image1.putalpha(128)
gif1 = ImageTk.PhotoImage(image1)

# gif1 = PhotoImage(file = 'aqua.png')
# next line will not work in my case
gif1 = gif1.subsample(5)

canvas.create_image(0, 0, image = gif1, anchor = NW)
mainloop()

Upvotes: 1

Views: 896

Answers (1)

sciroccorics
sciroccorics

Reputation: 2427

You can use the resize method included in the Image class. Here is the modified code:

from tkinter import *
from PIL import Image, ImageTk

canvas = Canvas(width = 200, height = 200)
canvas.pack(expand = YES, fill = BOTH)

image1 = Image.open('aqua.png')
image1.putalpha(128)
image1 = image1.resize((image1.width//5,image1.height//5))
gif1 = ImageTk.PhotoImage(image1)

canvas.create_image(0, 0, image = gif1, anchor = NW)
mainloop()

Upvotes: 3

Related Questions