Wednesday, December 19, 2018

codingdirectional: Convert an image from one format to another with pillow

Hello again and in this article, we will continue to explore what else can the pillow module do besides displaying a picture on the screen as we have already seen it before in the previous article. In this article, we will convert a picture from one format to another with the help of the pillow module. This module will be able to convert a picture from the jpg format to the png format but not vice versa. Below is the entire code, if you have missed out the tkinter part of the code then it is better for you to read the previous article about it.

from PIL import Image as pimage
from tkinter import *
from tkinter import filedialog
import os

win = Tk() # Create instance
win.title("Display Picture") # Add a title
win.resizable(0, 0) # Disable resizing the GUI
win.configure(background='black') # change background color

#  Create a label
aLabel = Label(win, text="Click on below button to manipulate an image!", anchor="center", padx=13, pady=10, relief=RAISED,)
aLabel.grid(column=0, row=0, sticky=W+E)
aLabel.configure(foreground="white")
aLabel.configure(background="black")
aLabel.configure(wraplength=160)

# Open an image file
def openImage():
    fullfilename = filedialog.askopenfilename(initialdir="/", title="Select a file", filetypes=[("Image files", "*.jpg; *.png")]) # select png or jpg image file from the hard drive
    
    if(fullfilename != ''):
        f, e = os.path.splitext(fullfilename)
        f = f + '.png' # the new output file format
        im = pimage.open(fullfilename).save(f)

action_pic = Button(win, text="Open Image", command=openImage, padx=2)
action_pic.grid(column=0, row=1, sticky=E+W)
action_pic.configure(background='black')
action_pic.configure(foreground='white')

win.mainloop()

That is it After you have selected any jpg image file this program will convert that image file to the png format type.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...