Taking Screenshots using pyscreenshot in Python

Share your love

Taking screenshots programmatically in Python can be useful for various purposes, such as capturing specific parts of your screen, automating tasks, or creating documentation. In this blog, we’ll explore how to take screenshots using the pyscreenshot library step by step. Let’s get started!

Taking Screenshots using pyscreenshot in Python

1. Introduction to pyscreenshot:

The pyscreenshot library provides a simple way to capture screenshots in Python. It acts as a thin layer over existing backends and allows you to take screenshots of the entire screen or specific regions.

2. Installation:

Before using pyscreenshot, make sure you have the pillow (PIL) package installed. You can install it using the following command:

pip install pillow

3. Capturing Full Screen:

Let’s start by capturing the entire screen and saving it to a file. We’ll use the grab() function from pyscreenshot.

Python

import pyscreenshot

# Capture the entire screen
image = pyscreenshot.grab()

# Display the captured screenshot (optional)
image.show()

# Save the screenshot to a file
image.save("full_screen_screenshot.png")

AI-generated code. Review and use carefully. More info on FAQ.

In the above code:

  • We use pyscreenshot.grab() to capture the full screen.
  • The image.show() line displays the captured screenshot (you can omit this if you don’t want to view it).
  • Finally, we save the screenshot to a file named “full_screen_screenshot.png”.

4. Capturing a Part of the Screen:

If you want to capture only a specific region of the screen, you can provide pixel coordinates to the grab() function. Here’s an example:

Python

# Capture a specific part of the screen (e.g., from (10, 10) to (500, 500))
partial_image = pyscreenshot.grab(bbox=(10, 10, 500, 500))

# Display the partial screenshot (optional)
partial_image.show()

# Save the screenshot to a file
partial_image.save("partial_screenshot.png")

AI-generated code. Review and use carefully. More info on FAQ.

In the above code:

  • We use bbox=(10, 10, 500, 500) to specify the region to capture (from (10, 10) to (500, 500)).
  • Adjust the coordinates according to your desired area.

5. Conclusion:

Written by: Piyush Patil

You’ve now learned how to take screenshots using pyscreenshot in Python. Feel free to explore more features of this library, such as capturing specific windows or custom regions. Happy coding!

Share your love