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
from pathlib import Path
from PIL import Image
# Open a select file dialog (a bit ugly on my OS)
file_path_str = askopenfilename() # '' if cancelled
if file_path_str: # guards against a cancelled dialog
file_path = Path(file_path_str) # a pathlib.Path object from the str
new_name = file_path.stem + '_altered' + file_path.suffix # keep suffix
# Make it output a PNG if you want LA mode to keep alpha
# new_name = file_path.stem + '_altered.png' maybe I should check for PNGs?
output_path = file_path.parent / new_name
try: # to handle any exceptions (runtime errors while converting/saving)
with Image.open(file_path) as im: # load image
altered_im = im.convert('L') # to grayscale (use 'LA' to keep alpha)
altered_im.save(output_path) # save image
print(f'Saved {output_path.name}!')
except Exception as err: # ... treat exception
print(err)