pythonbytescreenshotpython-mss

Take screenshot without writing to disk


I want to have a python script that can take a screenshot without saving it directly to the disk immediately. Basically is there a module with a function that returns the raw bytes that I can then write into a file by myself manually?

import some_screenshot_module
raw_data = some_screenshot_module.return_raw_screenshot_bytes()
f = open('screenshot.png','wb')
f.write(raw_data)
f.close()

I have already checked out mss, pyscreenshot and PIL yet I could not find what I needed. I found a function that looked like what I was looking for, called frombytes. However after retrieving the bytes from the frombytes function and saving it into a file I couldn't view it not as a .BMP,.PNG,.JPG. Is there a function that returns the raw bytes that I can save into a file by myself or perhaps a module with a function like that?


Solution

  • As of MSS 3.1.2, with the commit dd5298, you can do that easily:

    import mss
    import mss.tools
    
    
    with mss.mss() as sct:
        # Use the 1st monitor
        monitor = sct.monitors[1]
    
        # Grab the picture
        im = sct.grab(monitor)
    
        # Get the entire PNG raw bytes
        raw_bytes = mss.tools.to_png(im.rgb, im.size)
    
        # ...
    

    The update is already available on PyPi.


    Original answer

    Using the MSS module, you can access to raw bytes:

    import mss
    import mss.tools
    
    
    with mss.mss() as sct:
        # Use the 1st monitor
        monitor = sct.monitors[1]
    
        # Grab the picture
        im = sct.grab(monitor)
    
        # From now, you have access to different attributes like `rgb`
        # See https://python-mss.readthedocs.io/api.html#mss.tools.ScreenShot.rgb
        # `im.rgb` contains bytes of the screen shot in RGB _but_ you will have to
        # build the complete image because it does not set needed headers/structures
        # for PNG, JPEG or any picture format.
        # You can find the `to_png()` function that does this work for you,
        # you can create your own, just take inspiration here:
        # https://github.com/BoboTiG/python-mss/blob/master/mss/tools.py#L11
    
        # If you would use that function, it is dead simple:
        # args are (raw_data: bytes, (width, height): tuple, output: str)
        mss.tools.to_png(im.rgb, im.size, 'screenshot.png')
    

    Another example using part of the screen: https://python-mss.readthedocs.io/examples.html#part-of-the-screen

    Here is the documentation for more informations: https://python-mss.readthedocs.io/api.html