I wrote this to demo a quick #Python#Pillow#PIL conversion of an image to grayscale with a dialog to select the file... then applied it to a picture of me and @rennerocha
taken by John as we were flying back home after wonderful #PyConUS24 :)
from tkinter.filedialog import askopenfilename<br></br>from pathlib import Path<br></br><br></br>from PIL import Image<br></br><br></br># Open a select file dialog (a bit ugly on my OS)<br></br>file_path_str = askopenfilename() # '' if cancelled<br></br>if file_path_str: # guards against a cancelled dialog<br></br> file_path = Path(file_path_str) # a pathlib.Path object from the str<br></br> new_name = file_path.stem + '_altered' + file_path.suffix # keep suffix<br></br> # Make it output a PNG if you want LA mode to keep alpha<br></br> # new_name = file_path.stem + '_altered.png' maybe I should check for PNGs?<br></br> output_path = file_path.parent / new_name<br></br> try: # to handle any exceptions (runtime errors while converting/saving)<br></br> with Image.open(file_path) as im: # load image<br></br> altered_im = im.convert('L') # to grayscale (use 'LA' to keep alpha)<br></br> altered_im.save(output_path) # save image<br></br> print(f'Saved {output_path.name}!')<br></br> except Exception as err: # ... treat exception<br></br> print(err)<br></br>
This weekend is the perfect time to apply to the #pyConUS24 Maintainers Summit! Organized by @feynudibranch, @inessapawson, and @leahawasser, the Maintainers Summit brings together the #Python community to share best practices in developing sustainable projects and nurturing thriving communities.