Перейти к содержимому

Python как сделать скриншот экрана

  • автор:

Python-screenshot

Python library to make screen captures and save the images to the cwd

python-screenshot

Python library to make screen captures and save the images to the current working directory.

Installing:

  • Download the source, and run python setup.py build install

Examples:

  • Importing the library:
  • Output image size defaults to 800×450. A custom size can be set when the ScreenShot object is instantiated:
  • Taking a screenshot: this saves the screenshot to the current working directory as a .png file

The system time at the moment the screenshot was taken is used as the filename

How to take screenshots using python?

Python is a widely used general-purpose language. It allows performing a variety of tasks. One of them can be taking a screenshot. It provides a module named pyautogui which can be used to take the screenshot. This module along with NumPy and OpenCV provides the way to manipulate and save the images (screenshot in this case)

pyautogui takes pictures as a PIL(python image library) which supports opening, manipulating, and saving many different image file formats. Then we need to convert the image to NumPy array, so that it can be converted from RGB to BGR because when the image file is read with the OpenCV using imread() , the order of colors should be BGR (blue, green, red).

How To Take A Screenshot In Python Using PIL

In this tutorial, I will demonstrate how to take a screenshot using PIL in Python. Window, macOS and Linux are all supported.

PIL (Python Imaging Library / Pillow) is a Python library that adds support for opening, manipulating, and saving many different image file formats. It has a very friendly API with lots of help online including good documentation.

PIL supports Windows macOS and Linux and supports many versions of Python; see the installation notes to identify which version of PIL you will need for the version of Python you are using. At the time of wiring this, PIL 7 has been released and supports Python 3.8 — 3.5.

To install PIL, execute the following in a terminal:

To install an older version of PIL, execute python -m pip install pip=<version> eg. python -m pip install pip=7.2.0 . You can find older versions released in the release notes.

To validate it was installed correctly, go to IDLE or a python shell and execute:

If no import error is raised, it was installed successfully.

I Can’t Import PIL

Make sure you have executed the install command above; if you’re not sure you have executed it already, it is safe to execute it a second time.

If there were no errors when installing it and it says PIL is installed successfully, make sure you’re 100% sure that you installed PIL in the same distribution of Python that you’re trying to import it in. Go to my tutorial on How to Manage Multiple Python Distributions if you’re having some issues or are unsure about this.

Taking A Screenshot

To take a screenshot, we first need to import the ImageGrab module from PIL.

After we have the ImageGrab module, we can call .grab() to take a screenshot

On Linux, you must be using PIL 7.1.0 or higher for this to work; see release notes.

Viewing The Screenshot

To view the screenshot, we can call .show() on the returned Image object. For example, using the code from above:

Executing this will open the screenshot in your default image viewer. If you have more than one display, you will notice that this screenshot is only of the first display; I will expand on this further below.

Here is an example of a screenshot I took:

Screenshot Main Monitor

Saving The Screenshot

Saving images in PIL is very easy, calling .save() on the returned Image object will allow us to save the image into a file.

Now if you go and open the file filepath («my_image.png» in the current working directory for this example), you will see the screenshot has been saved.

If you provide a file path with an extension of a supported image format, you can omit the format.

Saving To A File Object

If you have a file already open in write mode or want to save the image to a file object, you can pass that instead of the filename. For example:

Taking A Screenshot Of A Different Display

Back when we took a screenshot using ImageGrab.grab() , it only captured the main display. To take a screenshot of all displays, we can pass all_screens=True :

Please note that all_screens is currently only supported in Windows

Now when you call screenshot.show() , you will see that multiple monitors are now displayed. Here is an example of my monitors:

Screenshot All Monitors

Now that you have this larger image, you can crop it using other methods in PIL: How to crop an image using PIL.

Using MSS to Screenshot Each Displays

I also have a tutorial How To Take A Screenshot In Python Using MSS which goes over how to take screenshots using the Python MSS library. The tutorial is very similar, however MSS has better support for screenshots of different individual displays (including macOS and Windows).

Owner of PyTutorials and creator of auto-py-to-exe. I enjoy making quick tutorials for people new to particular topics in Python and tools that help fix small things.

Python как сделать скриншот экрана

webfanat вконтакте webfanat youtube

  • Главная /
  • PYTHON /
  • Скриншоты python

Скриншоты python

Скриншоты python

Всем привет. Сегодня мы рассмотрим как делать скриншоты в python используя модуль pyautogui. Поехали!

Для начала подключаем модуль pyautogui.

И теперь для того чтобы сделать скриншот, достаточно воспользоваться методом screenshot() который предоставляет нам данный модуль.

В результате выполнения данного кода мы сделаем скриншот всего экрана. Сам скриншот сохранится в виде изображения с названием screenshot и в формате png. Которые мы указали в самом методе screenshot(). Найти изображение вы сможете рядом с файлом программы. На выходе метод screenshot() возвращает объект изображения.

Если мы хотим сделать скриншот определенной части экрана. Можно воспользоваться свойством region.

Здесь в свойстве region мы указали что у нас будет снят левый верхний угол размером 300×400 пикселей. То есть первые две координаты(0,0) отвечают за левый верхний угол, а вторые(300, 400) за размер области экрана.

Вот мы у научились делать скриншоты в python. Помимо этого модуль pyautogui предоставляет нам возможность нахождения кусочков изображения в области где мы осуществляем скриншот.

Допустим у меня есть такой кусочек изображения.

mozilla firefox

Кто не знает это значок браузера mozilla firefox.

И теперь я хочу на своем рабочем столе найти координаты нахождения данного значка.

screenshot python

Для этого я использую метод locateOnScreen() и в качестве аргумента передаю ему изображение со значком.

В результате работы данный метод возвращает координаты где было найдено соответствие с изображением значка в области всего экрана.

Если я к примеру удалю ярлык браузера mozilla firefox из области экрана. Следовательно соответствия метод locateOnScreen() уже не найдет и нам вернется значение None.

screenshot python pyautogui

Вот так с помощью метода locateOnScreen() вы можете в области экрана искать соответствия по картинке шаблону.

На этом у меня все. Надеюсь данная статья была для вас полезна. Если остались вопросы пишите их в комментариях к данной статье или группе в

А я с вами прощаюсь. Желаю успехов и удачи! Пока.

Оцените статью:
Статьи
Комментарии

Внимание. Комментарий теперь перед публикацией проходит модерацию

Все комментарии отправлены на модерацию

Реклама

Запись экрана

Данное расширение позволяет записывать экран и выводит видео в формате webm

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Школа онлайн с государственным аттестатом