Importerror imagegrab is macos and windows only

from PIL import Image, ImageGrab, ImageChops, ImageOps

When I do make run in the root folder, I get this issue:

python3 orchestrator/main.py Traceback (most recent call last): File "orchestrator/main.py", line 1, in <module> from PIL import Image, ImageGrab, ImageChops, ImageOps File "/usr/lib/python3/dist-packages/PIL/ImageGrab.py", line 26, in <module> raise ImportError("ImageGrab is macOS and Windows only") ImportError: ImageGrab is macOS and Windows only make: *** [Makefile:5: run] Error 1

Is this meant to be ran in Windows/macOS terminals after creating all the files in Linux?

---------------------------------------------------------------------------
FailedBackendError                        Traceback (most recent call last)
<ipython-input-32-df871433ae1f> in <module>
      1 import pyscreenshot as pyss
      2 
----> 3 pyss.grab()

~/.local/lib/python3.7/site-packages/pyscreenshot/__init__.py in grab(bbox, childprocess, backend)
     41                     otherwise back-end is automatic
     42     """
---> 43     return _grab(childprocess=childprocess, backend=backend, bbox=bbox)
     44 
     45 

~/.local/lib/python3.7/site-packages/pyscreenshot/__init__.py in _grab(childprocess, backend, bbox, filename)
     27     if childprocess:
     28         log.debug('running "%s" in child process', backend)
---> 29         return childprocess_grab(_grab_simple, backend, bbox)
     30     else:
     31         return _grab_simple(backend, bbox, filename)

~/.local/lib/python3.7/site-packages/pyscreenshot/childproc.py in childprocess_grab(_grab_simple, backend, bbox)
     32 def childprocess_grab(_grab_simple, backend, bbox):
     33     if POPEN:
---> 34         return childprocess_grab_popen(backend, bbox)
     35     else:
     36         return run_in_childprocess(_grab_simple, codec, backend, bbox)

~/.local/lib/python3.7/site-packages/pyscreenshot/childproc.py in childprocess_grab_popen(backend, bbox)
     52         if p.return_code != 0:
     53             # log.debug(p)
---> 54             raise FailedBackendError(p)
     55 
     56         data = open(filename, "rb").read()

FailedBackendError: <EasyProcess cmd_param=['/usr/bin/python3', '-m', 'pyscreenshot.cli.grab_to_file', '/tmp/pyscreenshotqpisq00z/screenshot.png', '0', '0', '0', '0', '--backend', ''] cmd=['/usr/bin/python3', '-m', 'pyscreenshot.cli.grab_to_file', '/tmp/pyscreenshotqpisq00z/screenshot.png', '0', '0', '0', '0', '--backend', ''] oserror=None return_code=-6 stdout="" stderr="qt.qpa.xcb: could not connect to display 
qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Available platform plugins are: eglfs, linuxfb, minimal, minimalegl, offscreen, vnc, xcb.
" timeout_happened=False>

September 15, 2022
JavaScript
  • Source code for PIL.ImageGrab
  • Python PIL | ImageGrab.grab() method
  • Python | Using PIL ImageGrab and PyTesseract
  • Note.nkmk.me
  • Grab Image from Clipboard in Python with Pillow
  • Python screenshot library, replacement for the Pillow ImageGrab module
  • PIL and Python27 — Save a screengrab?
  • ImageGrab.grab(bbox) and Image.getpixel() Used together

Source code for PIL.ImageGrab

Toggle Light / Dark / Auto color theme. Toggle table of contents sidebar.
Pillow (PIL Fork) 9.2.0 documentation

#
# The Python Imaging Library
# $Id$
#
# screen grabber
#
# History:
# 2001-04-26 fl  created
# 2001-09-17 fl  use builtin driver, if present
# 2002-11-19 fl  added grabclipboard support
#
# Copyright (c) 2001-2002 by Secret Labs AB
# Copyright (c) 2001-2002 by Fredrik Lundh
#
# See the README file for information on usage and redistribution.
#

import os
import shutil
import subprocess
import sys
import tempfile

from . import Image


[docs]def grab(bbox=None, include_layered_windows=False, all_screens=False, xdisplay=None):
    if xdisplay is None:
        if sys.platform == "darwin":
            fh, filepath = tempfile.mkstemp(".png")
            os.close(fh)
            args = ["screencapture"]
            if bbox:
                left, top, right, bottom = bbox
                args += ["-R", f"{left},{top},{right-left},{bottom-top}"]
            subprocess.call(args + ["-x", filepath])
            im = Image.open(filepath)
            im.load()
            os.unlink(filepath)
            if bbox:
                im_resized = im.resize((right - left, bottom - top))
                im.close()
                return im_resized
            return im
        elif sys.platform == "win32":
            offset, size, data = Image.core.grabscreen_win32(
                include_layered_windows, all_screens
            )
            im = Image.frombytes(
                "RGB",
                size,
                data,
                # RGB, 32-bit line padding, origin lower left corner
                "raw",
                "BGR",
                (size[0] * 3 + 3) & -4,
                -1,
            )
            if bbox:
                x0, y0 = offset
                left, top, right, bottom = bbox
                im = im.crop((left - x0, top - y0, right - x0, bottom - y0))
            return im
        elif shutil.which("gnome-screenshot"):
            fh, filepath = tempfile.mkstemp(".png")
            os.close(fh)
            subprocess.call(["gnome-screenshot", "-f", filepath])
            im = Image.open(filepath)
            im.load()
            os.unlink(filepath)
            if bbox:
                im_cropped = im.crop(bbox)
                im.close()
                return im_cropped
            return im
    # use xdisplay=None for default display on non-win32/macOS systems
    if not Image.core.HAVE_XCB:
        raise OSError("Pillow was built without XCB support")
    size, data = Image.core.grabscreen_x11(xdisplay)
    im = Image.frombytes("RGB", size, data, "raw", "BGRX", size[0] * 4, 1)
    if bbox:
        im = im.crop(bbox)
    return im


[docs]def grabclipboard():
    if sys.platform == "darwin":
        fh, filepath = tempfile.mkstemp(".jpg")
        os.close(fh)
        commands = [
            'set theFile to (open for access POSIX file "'
            + filepath
            + '" with write permission)',
            "try",
            "    write (the clipboard as JPEG picture) to theFile",
            "end try",
            "close access theFile",
        ]
        script = ["osascript"]
        for command in commands:
            script += ["-e", command]
        subprocess.call(script)

        im = None
        if os.stat(filepath).st_size != 0:
            im = Image.open(filepath)
            im.load()
        os.unlink(filepath)
        return im
    elif sys.platform == "win32":
        fmt, data = Image.core.grabclipboard_win32()
        if fmt == "file":  # CF_HDROP
            import struct

            o = struct.unpack_from("I", data)[0]
            if data[16] != 0:
                files = data[o:].decode("utf-16le").split("\0")
            else:
                files = data[o:].decode("mbcs").split("\0")
            return files[: files.index("")]
        if isinstance(data, bytes):
            import io

            data = io.BytesIO(data)
            if fmt == "png":
                from . import PngImagePlugin

                return PngImagePlugin.PngImageFile(data)
            elif fmt == "DIB":
                from . import BmpImagePlugin

                return BmpImagePlugin.DibImageFile(data)
        return None
    else:
        raise NotImplementedError("ImageGrab.grabclipboard() is macOS and Windows only")

Python PIL | ImageGrab.grab() method

The ImageGrab module can be used to copy the contents of the screen or the
clipboard to a PIL image memory. PIL.ImageGrab.grab () method takes a snapshot
of the screen. The pixels inside the bounding box are returned as an “RGB”
image on Windows or “RGBA” on macOS. If the bounding box is omitted, the
entire screen is copied.

Syntax: PIL.ImageGrab.grab(bbox=None)

parameters: 
bbox: What region to copy. Default is the entire screen.

Returns: An image

Python | Using PIL ImageGrab and PyTesseract

ImageGrab is a Python module that helps to capture the contents of the screen.
PyTesseract is an Optical Character Recognition (OCR) tool for Python.
Together they can be used to read the contents of a section of the screen.
Installation – Pillow (a newer version of PIL) pip install Pillow PyTesseract
pip install pytesseract

pip install Pillow


pip install pytesseract

Note.nkmk.me

ImageGrab.grab () — Pillow (PIL Fork) 9.1.0 documentation You can also work
with the clipboard with pyperclip. Copy and paste text to the clipboard with
pyperclip in Python Sponsored Link how to use ImageGrab.grabclipboard ()
ImageGrab.grabclipboard () returns the image copied on the clipboard. The
returned Image object can be processed in Pillow.

from PIL import ImageGrab, Image

img = ImageGrab.grabclipboard()
print(img)
# <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=200x71 at 0x105E68700>

print(isinstance(img, Image.Image))
# True

print(img.size)
# (200, 71)

print(img.mode)
# RGB

img.save('data/temp/clipboard_image.jpg')



img = ImageGrab.grabclipboard()
print(img)
# None

Grab Image from Clipboard in Python with Pillow

This uses the ImageGrab module. Check out the ImageGrab documentation for more
details. Not only can it grab an image from the clipboard, it can actually
grab directly from the screen taking full or partial screenshots! # pip
install pillow from PIL import ImageGrab img = ImageGrab.grabclipboard() # or
ImageGrab.grab() to grab the whole screen

pip install pillow


# pip install pillowfrom PIL import ImageGrabimg = ImageGrab.grabclipboard()# or ImageGrab.grab() to grab the whole screen!print(img)# <PIL.BmpImagePlugin.DibImageFile image mode=RGB size=380x173 at 0x16A43064DA0>


AttributeError: 'NoneType' object has no attribute 'save'


from PIL import ImageGrabimg = ImageGrab.grabclipboard()        # Save the image to diskimg.save('paste.png', 'PNG')img.save('paste.jpg', 'JPEG')


from PIL import ImageGrabimport ioimg = ImageGrab.grabclipboard()# Store the bytes in a byte streamimg_bytes = io.BytesIO()img.save(img_bytes, format='PNG')print(img_bytes.getvalue())


<!-- Base64 image example --><img src="data:image/png;base64, AAAnr4nykAwk9WqzMg==" />


from PIL import ImageGrabimport ioimport codecs# Pull image from clibpoardimg = ImageGrab.grabclipboard()# Get raw bytesimg_bytes = io.BytesIO()img.save(img_bytes, format='PNG')# Convert bytes to base64base64_data = codecs.encode(img_bytes.getvalue(), 'base64')# Convert base64 data to a stringbase64_text = codecs.decode(base64_data, 'ascii')# Create an HTML img tag with data embeddedhtml_img_tag = "<img src="data:image/png;base64, %s" />" % base64_text# Print HTML tag to console (might be long).# You can put this img tag in to HTML and the browser# will render the image.print(html_img_tag)

Python screenshot library, replacement for the Pillow ImageGrab module

on Linux

It was created because PIL ImageGrab module worked on Windows only, but now
Linux and macOS are also supported by Pillow. There are some features in
pyscreenshot which can be useful in special cases: flexible backends, Wayland
support, sometimes better performance, optional subprocessing.

$ python3 -m pip install Pillow pyscreenshot



# pyscreenshot/examples/grabfullscreen.py

"Grab the whole screen"
import pyscreenshot as ImageGrab

# grab fullscreen
im = ImageGrab.grab()

# save image file
im.save("fullscreen.png")

# pyscreenshot/examples/grabbox.py

"Grab the part of the screen"
import pyscreenshot as ImageGrab

# part of the screen
im = ImageGrab.grab(bbox=(10, 10, 510, 510))  # X1,Y1,X2,Y2

# save image file
im.save("box.png")

# pyscreenshot/examples/virtdisp.py

"Create screenshot of xmessage with Xvfb"
from time import sleep

from easyprocess import EasyProcess
from pyvirtualdisplay import Display

import pyscreenshot as ImageGrab

with Display(size=(100, 60)) as disp:  # start Xvfb display
    # display is available
    with EasyProcess(["xmessage", "hello"]):  # start xmessage
        sleep(1)  # wait for diplaying window
        img = ImageGrab.grab()
img.save("xmessage.png")



$ python3 -m pyscreenshot.check.versions
python               3.8.5
pyscreenshot         2.3
pil                  8.0.1
mss                  6.1.0
scrot                1.2
grim                 ?.?
maim                 5.5.3
imagemagick          6.9.10
pyqt5                5.14.1
pyqt                 
pyside2              5.14.0
pyside               
wx                   4.0.7
pygdk3               3.36.0
mac_screencapture    
mac_quartz           
gnome_dbus           ?.?
gnome-screenshot     3.36.0
kwin_dbus            ?.?

$ python3 -m pyscreenshot.check.speedtest

n=10
------------------------------------------------------
default                 1    sec    (  101 ms per call)
pil                     1.7  sec    (  166 ms per call)
mss                     1.9  sec    (  191 ms per call)
scrot                   0.97 sec    (   97 ms per call)
grim                    
maim                    1.4  sec    (  144 ms per call)
imagemagick             2.4  sec    (  235 ms per call)
pyqt5                   4.3  sec    (  429 ms per call)
pyqt                    
pyside2                 4.2  sec    (  423 ms per call)
pyside                  
wx                      4.1  sec    (  412 ms per call)
pygdk3                  2    sec    (  204 ms per call)
mac_screencapture       
mac_quartz              
gnome_dbus              1.4  sec    (  144 ms per call)
gnome-screenshot        3.8  sec    (  381 ms per call)
kwin_dbus               

$ python3 -m pyscreenshot.check.speedtest --childprocess 0

n=10
------------------------------------------------------
default                 0.11 sec    (   10 ms per call)
pil                     0.09 sec    (    8 ms per call)
mss                     0.15 sec    (   15 ms per call)
scrot                   0.95 sec    (   95 ms per call)
grim                    
maim                    1.5  sec    (  145 ms per call)
imagemagick             2.4  sec    (  235 ms per call)
pyqt5                   1.1  sec    (  114 ms per call)
pyqt                    
pyside2                 1.2  sec    (  118 ms per call)
pyside                  
wx                      0.43 sec    (   43 ms per call)
pygdk3                  0.16 sec    (   15 ms per call)
mac_screencapture       
mac_quartz              
gnome_dbus              1.5  sec    (  147 ms per call)
gnome-screenshot        3.8  sec    (  383 ms per call)
kwin_dbus               



import pyscreenshot as ImageGrab
im = ImageGrab.grab(backend="scrot")



# best performance
import pyscreenshot as ImageGrab
im = ImageGrab.grab(backend="mss", childprocess=False)

PIL and Python27 — Save a screengrab?

Here is the code from PIL import ImageGrab scrgrb = ImageGrab.grabclipboard ()
scrgrbnum = 0 def saveimg (): scrgrb.save («screengrab.jpeg + str (scrgrbnum +
1)», «JPEG») scrgrbnum = scrgrbnum + 1 saveimg () And I get this error

from PIL import ImageGrab
scrgrb = ImageGrab.grabclipboard()
scrgrbnum = 0

def saveimg():
    scrgrb.save("screengrab.jpeg + str(scrgrbnum + 1)", "JPEG")
    scrgrbnum = scrgrbnum + 1

saveimg()



Traceback (most recent call last):   File
 "C:/Python27/Programs/screengrab", line 10, in <module>
     saveimg()   File "C:/Python27/Programs/screengrab", line 7, in saveimg
     scrgrb.save("screengrab.jpeg + str(scrgrbnum + 1)", "JPEG") AttributeError: 'NoneType' object has no attribute 'save'



 import win32api, win32con, ImageGrab
 win32api.keybd_event(win32con.VK_SNAPSHOT, 1)
 im = ImageGrab.grabclipboard()
 im.save("screenshot.jpg", "JPEG")



scrgrb = ImageGrab.grabclipboard()



scrgrb = ImageGrab.grab()

ImageGrab.grab(bbox) and Image.getpixel() Used together

The bounding box is a (left_x, top_y, right_x, bottom_y) tuple, so with the
values (500, 500, 600, 700), the image has a width of 100 pixels and a height
of 200 pixels. That explains why im.getpixel (510, 510) doesn’t work — the
coordinate 510 is outside of the image.

im = ImageGrab.grab(bbox=(500, 500, 600, 700)
print(im.getpixel(510, 510))
print(im.getpixel(10, 10))

Repository URL to install this package:

Pillow

/

Tests

/

test_imagegrab.py

from helper import unittest, PillowTestCase, on_appveyor

import sys

try:
    from PIL import ImageGrab

    class TestImageGrab(PillowTestCase):

        @unittest.skipIf(on_appveyor(), "Test fails on appveyor")
        def test_grab(self):
            im = ImageGrab.grab()
            self.assert_image(im, im.mode, im.size)

        @unittest.skipIf(on_appveyor(), "Test fails on appveyor")
        def test_grab2(self):
            im = ImageGrab.grab()
            self.assert_image(im, im.mode, im.size)

except ImportError:
    class TestImageGrab(PillowTestCase):
        def test_skip(self):
            self.skipTest("ImportError")


class TestImageGrabImport(PillowTestCase):

    def test_import(self):
        # Arrange
        exception = None

        # Act
        try:
            from PIL import ImageGrab
            ImageGrab.__name__  # dummy to prevent Pyflakes warning
        except Exception as e:
            exception = e

        # Assert
        if sys.platform in ["win32", "darwin"]:
            self.assertIsNone(exception)
        else:
            self.assertIsInstance(exception, ImportError)
            self.assertEqual(str(exception),
                             "ImageGrab is macOS and Windows only")


if __name__ == '__main__':
    unittest.main()

POCO, ACE, Loki и другие продвинутые C++ библиотеки

NullReferenced 13.05.2025

В C++ разработки существует такое обилие библиотек, что порой кажется, будто ты заблудился в дремучем лесу. И среди этого многообразия POCO (Portable Components) – как маяк для тех, кто ищет. . .

Паттерны проектирования GoF на C#

UnmanagedCoder 13.05.2025

Вы наверняка сталкивались с ситуациями, когда код разрастается до неприличных размеров, а его поддержка становится настоящим испытанием. Именно в такие моменты на помощь приходят паттерны Gang of. . .

Создаем CLI приложение на Python с Prompt Toolkit

py-thonny 13.05.2025

Современные командные интерфейсы давно перестали быть черно-белыми текстовыми программами, которые многие помнят по старым операционным системам. CLI сегодня – это мощные, интуитивные и даже. . .

Конвейеры ETL с Apache Airflow и Python

AI_Generated 13.05.2025

ETL-конвейеры – это набор процессов, отвечающих за извлечение данных из различных источников (Extract), их преобразование в нужный формат (Transform) и загрузку в целевое хранилище (Load). . . .

Выполнение асинхронных задач в Python с asyncio

py-thonny 12.05.2025

Современный мир программирования похож на оживлённый мегаполис – тысячи процессов одновременно требуют внимания, ресурсов и времени. В этих джунглях операций возникают ситуации, когда программа. . .

Работа с gRPC сервисами на C#

UnmanagedCoder 12.05.2025

gRPC (Google Remote Procedure Call) — открытый высокопроизводительный RPC-фреймворк, изначально разработанный компанией Google. Он отличается от традиционых REST-сервисов как минимум тем, что. . .

CQRS (Command Query Responsibility Segregation) на Java

Javaican 12.05.2025

CQRS — Command Query Responsibility Segregation, или разделение ответственности команд и запросов. Суть этого архитектурного паттерна проста: операции чтения данных (запросы) отделяются от операций. . .

Шаблоны и приёмы реализации DDD на C#

stackOverflow 12.05.2025

Когда я впервые погрузился в мир Domain-Driven Design, мне показалось, что это очередная модная методология, которая скоро канет в лету. Однако годы практики убедили меня в обратном. DDD — не просто. . .

Исследование рантаймов контейнеров Docker, containerd и rkt

Mr. Docker 11.05.2025

Когда мы говорим о контейнерных рантаймах, мы обсуждаем программные компоненты, отвечающие за исполнение контейнеризованных приложений. Это тот слой, который берет образ контейнера и превращает его в. . .

Micronaut и GraalVM — будущее микросервисов на Java?

Javaican 11.05.2025

Облачные вычисления безжалостно обнажили ахиллесову пяту Java — прожорливость к ресурсам и медлительный старт приложений. Традиционные фреймворки, годами радовавшие корпоративных разработчиков своей. . .

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как переустановить windows без потери office
  • Запись флешки с windows из под linux
  • Как включить состояние безопасной загрузки на windows 11 gigabyte
  • Как открыть фото формата heic на windows 10
  • Microsoft visual c все пакеты для windows 10 x64 что это