Loading...
Random Pearls Random Pearls New Menu
  • All Pearls
    • Random Pearls
  • Coding and Development - Reference …
    • Coding and Development - Reference …  (parent page)
    • Information Technology  (parent page of Coding and Development - Reference …)
  • New Menu
  • Authors
  •  
  • Contact Us
  • Sign up
  • Login
    Forgot Password?
  • Follow us on
Image Back to Top Back to top
Language Preference
This website has language specific content. Here you can set the language(s) of your preference.

This setting does not affect the current page. It is used only for filtering pages in menus, preview tiles and search results.

It can be changed any time by using the login menu (if you are logged in) or by clicking the Language button on the left bottom of the page.
Log in to save your preference permanently.



If you do not set this preference, you may see a header like This page has 'language_name' content in page preview tiles.
Search
  • Navigation
  • Similar
  • Author
  • More...
You are here:
All Content / Science and Technology / Information Technology / Coding and Development - Reference … / Save Windows Screenshot as jpg File using a Shortcut …
Table of Contents

Subscribe to Our Newsletter
Follow us by subscribing to our newsletter and navigate to the newly added content on this website directly from your inbox!
Login to subscribe to this page.
Categories  
Tags  
Author  
manisar
Author's Display Image

"Whenever you can, share. You never know who all will be able to see far away standing upon your shoulders!"

I write mainly on topics related to science and technology.

Sometimes, I create tools and animation.


Save Windows Screenshot as jpg File using a Shortcut Key

June 21, 2021

Author - manisar

Save any image from clipboard in general


Small and insignificant as it may seem, the transition from PrintScreen to Win+Shift+S has been really helpful for technical and casual Windows users alike. But there is something that had been of a bit of a bother for me.

After you have captured a screenshot, you get a picture in the clipboard. If you are using a photo editor (such as Paint or paint.net), or any client app capable of grabbing this picture from clipboard (such as WhatsApp Web) you can use it for working with the screenshot. But what if you just wanted the picture as a file so that you can use it in any way you wanted, e.g. for uploading through a browser file upload, or simply using it later for something?

Same for images copied into clipboard from other apps such as Word, browser etc.

For long I was using Paint to capture the image after hitting Win+Shift+S, or after copying them from other apps, and then using the save feature in Paint. A bit of a hassle.

Finally I came up with the following using Python. So this is my workflow now:

  1. Capture the screenshot using Win+Shift+S, or copy image from another app.

  2. Open any folder, where I want 3. below to save my image as a .jpg file.
    I use another Windows Desktop shortcut key for opening a designated folder for this purpose.

  3. Invoke a Python script using Windows Desktop shortcut key for saving the file.
    This script saves the file with a default name (I use tempfile.jpg), and immediately takes Windows to file rename mode for this file. All I have to do is type the new desired name for this file.

Thus, with these three sets of keystrokes, I get a .jpg file at my disposal.

  1. Win+Shift+S for taking the screenshot, or, right clicking in other apps and selecting 'Copy Image'
  2. Ctrl+Alt+F for opening a designated folder (optional)
  3. Ctrl+Alt+I for saving the image as a file and letting me rename the file immediately

The shortcuts keys F and I are what I chose, you can choose any another key.
I'll now explain all the steps needed for setting up this mechanism.

Prerequisites

The following is for Windows users. Linux and Mac users will have to tweak the scripts.

  • Install Python.
  • Along with running .py files, we'll also need to be able to run .pyw files. So create a temporary .pyw file anywhere, right click on and change Opens with to: C:\Program Files (x86)\Python37-32\pythonw.exe.
  • We'll need the python package installer pip which automatically comes with Python 2 >=2.7.9 or Python 3 >=3.4.
    Otherwise you can get pip using:
    curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
    python get-pip.py
  • After installing Python, we need to make a slight adjustment in Windows.
    This is needed so that python scripts receive and processes any arguments correctly.
    • Open Windows registry editor - regedit.
    • Go to Computer\HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command
    • Change the value of (Default) key to "C:\Program Files (x86)\Python37-32\python.exe" "%1" "%*"
    • Similarly, in Computer\HKEY_CLASSES_ROOT\Applications\pythonw.exe\shell\open\command, make the default key "C:\Program Files (x86)\Python37-32\pythonw.exe" "%1":
      The paths to python.exe and pythonw.exe may be different for you, don't change them, just add the arguments in the end. Remember to include the quotes.

Script for Opening a Specific Folder

  • Copy and paste the code given below to any file on your computer ending with .pyw (say Script1.pyw).
    This code is for opening a designated folder.
    The .pyw extension is for running this script without invoking a command line window which we don't need for this functionality.
#!/usr/bin/env python3
import os

tempPath = r"D:\Images"

def main():
    os.system('start ' + tempPath)
          
if __name__ == "__main__":
    main()
  • Create a shortcut on your desktop for Script1.pyw.
  • Right click on this shortcut, go to the Shortcut tab, enter a key of your choice for Shortcut key (say F), and press Ok.
  • Now pressing Ctrl+Alt+F from anywhere will open the folder D:\Images.

Script for Saving The Image as a File

We need a few packages installed on top of your system level Python.
Run the following commands in Windows cmd.

  • Check if you have PIL by running pip show PIL. If not, install pillow using pip install pillow.
  • pip install pywin32
  • pip install pyautogui

Now, copy and paste the code given below to any file on your computer ending with .pyw (say Script2.pyw). Change the startingPath to the path of the folder you used in Script1.pyw.

On running this script, if it finds a Windows folder in foreground, it saves the image there, otherwise it will save the image file at startingPath.

#!/usr/bin/env python3
from PIL import ImageGrab
from PIL import Image
import os
from win32com.shell import shell # pywin32
import sys
import traceback
from pyautogui import hotkey # pyautogui
import time
import win32gui # pywin32
from win32com.client import Dispatch # pywin32

startingPath = r"D:\Images"

def launch_file_explorer(path, files):
    '''Given an absolute base path and names of its children (no path), open
up one File Explorer window with all the child files selected'''
    folder_pidl = shell.SHILCreateFromPath(path,0)[0]
    desktop = shell.SHGetDesktopFolder()
    shell_folder = desktop.BindToObject(folder_pidl, None, shell.IID_IShellFolder)
    name_to_item_mapping = dict([(desktop.GetDisplayNameOf(item, 0), item) for item in shell_folder])
    to_show = []
    for file in files:
        if not file in name_to_item_mapping:
            raise Exception('File: "%s" not found in "%s"' % (file, path))
        to_show.append(name_to_item_mapping[file])
    shell.SHOpenFolderAndSelectItems(folder_pidl, to_show, 1)

im = ImageGrab.grabclipboard() im = im.convert('RGB')
def main():
    if Image.isImageType(im):
        filename = 'tempfile.jpg'
        try:
            fullPath = os.path.join(startingPath,filename)
            im.save(fullPath,'JPEG', subsampling=0, quality=95)
            launch_file_explorer(os.path.dirname(fullPath),[os.path.basename(fullPath)])
        except Exception as ex:
            ex_type, ex_value, ex_traceback = sys.exc_info() # get current system exception
            trace_back = traceback.extract_tb(ex_traceback) # extract unformatter stack traces as tuples
            stack_trace = list() # format stacktrace

            for trace in trace_back:
                stack_trace.append("File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3]))

            print("Exception type : %s " % ex_type.__name__)
            print("Exception message : %s" %ex_value)
            print("Stack trace : %s" %stack_trace)
            input("Press enter to exit...")

def get_we(shell,handle):
    for win in shell.Windows():
        if win.hwnd == handle: return win
    return None
            
if __name__ == "__main__":
    hotkey('alt','tab')
    time.sleep(0.05)
    w = win32gui
    
    SHELL = Dispatch("Shell.Application")
    we = get_we(SHELL,w.GetForegroundWindow())
    if we:
        startingPath = we.LocationURL.replace("file:///","").replace("/","\\").replace("%20"," ")
    main()

  • Create a shortcut on your desktop for Script2.pyw.
  • Right click on this shortcut, go to the Shortcut tab, enter a key of your choice for Shortcut key (say I), and press Ok.
  • Now pressing Ctrl+Alt+I from anywhere will grab the image (if there is any) from clipboard and save it in the foreground folder or D:\Images. Right after saving the file, you will be taken to the file rename mode - simply enter the <new_filename>, you will have <new_filename>.jpg.

Note: You can change the image quality etc. by modifying the line im.save(fullPath,'JPEG', subsampling=0, quality=95) in the second script.

Happy screen capturing!

Advertisement
Advertisement
Close ad Ad

Advertisement
Close ad Ad

Advertisement
Close ad Ad

Return to Coding and Development - Reference and Tools

Tell us what you think (select text for formatting, or click )

Copyright © randompearls.com 2020

Privacy Policy