Tales of a GeekTrotter Binary Logbook

28Feb/121

Save your screenshots to a file in Python

Python allows you to quickly build useful applications.
Let say you're running the old Windows XP and need to take screenshots of your screen, directly saving the picture.
You might usually open Paint, paste, save (choosing the format you want to save as).
Well, fast enough, but could be improved isn't it?

The following piece of code grabs the image from the clipboard and directly prompts you where to save the file.
Depending on the filename you choose, it will automatically apply the correct compression (bmp/png/jpeg...) thanks to the Python Image Library (PIL).

In addition to the libraries bundled with Python you only need to install PIL, either from PIL or from PILLOW.

I personally chose pillow:

$ pypm install pillow
The following packages will be installed into "%APPDATA%\Python" (2.7):
 pillow-1.7.6
Hit: [pypm-free.activestate.com] pillow 1.7.6
Installing pillow-1.7.6
Fixing script %APPDATA%\Python\Scripts\pilconvert.py
Fixing script %APPDATA%\Python\Scripts\pildriver.py
Fixing script %APPDATA%\Python\Scripts\pilfile.py
Fixing script %APPDATA%\Python\Scripts\pilprint.py

You are now ready to run the script:

import os
from PIL import ImageGrab # from PIL or PILLOW
from Tkinter import Tk
from tkFileDialog import asksaveasfile
import tkMessageBox
import subprocess

if __name__=='__main__':
    
    # hide the Tk window
    root = Tk()
    root.withdraw()
    
    # grab the image from the clipboard
    myimage = ImageGrab.grabclipboard()
    
    # quit if it's not an image
    if myimage is None:
        msg = "The clipboard does not contain an image."
        tkMessageBox.showwarning("Error", msg)
        exit()
    
    # choose where to save the file
    fout = asksaveasfile(mode='w', defaultextension=".png")
    
    # quit if the user canceled saving the file
    if fout is None:
        exit()
    
    # finally, save the file (extension will dictate the compression)
    try:
        output = fout.name
        myimage.save(output)
    except Exception, e:
        msg = "Error: %s" % e
        tkMessageBox.showerror("Error", msg)
    else:
        filePath = os.path.abspath(output)
        #tkMessageBox.showinfo("Saved", filePath)
        subprocess.Popen(r'explorer /select,"'+filePath+'"')

To use it, simply hit the "Print Scrn" key and run the script.
Running the script is not that faster than starting Paint so you could create a shortcut to the desktop and create a Shortcut Key to the shortcut.

For example to set a shortcut to "Ctrl + Alt + P":

Now simply hit "Print Scrn", "Ctrl + Alt + P" and choose where to save the screenshot, that's it!