Search code examples
pythonwindowsscreenshot

How do you save a croppable png image of your screen to your desktop using python windows?


I am having trouble saving a full screen image/screenshot to my desktop using python. I have tried

from PIL import ImageGrab
import os
img = img.crop((10, 10, 650, 2000))
mageGrab.grab().save(r"screen_capture.png")
stuffs = process_image(Image.open(r"C:\Users\jacro\pycharmprojects\untitled\screen_capture.png"))
stuffs.save(SCREEN_DIR + r"\screen.png")

But get the picture attached. This happens when I crop the last parameter differently too. Plz help.

image 1


Solution

  • I am assuming you need to crop the screenshot to desired size. If you are using static values, you will need to be careful as values may change with resolution. You can do this statically as below (re-arranging your values).

    img2 = img.crop((0, -1000, 2000, 650))
    

    However, preferred way is dynamically calculating crop co-ordinates. like below example ( Inspiration from here )

    from PIL import ImageGrab,Image
    import os
    
    ImageGrab.grab().save(r"screen_capture.png")
    img = Image.open(r".//screen_capture.png")
    image_width = img.size[0]
    image_height = img.size[1]
    horizontal_padding = (max(img.size) - image_width) / 2  #horizontal center 
    vertical_padding = (max(img.size) - image_height) / 2    #vertical center
    
    img3 = img.crop(
        (   -horizontal_padding,
            -vertical_padding,
            image_width + horizontal_padding,
            image_height + vertical_padding
        ))
    img3.save("img3.png")
    

    Centrally Cropped Screen-Capture enter image description here