Search code examples
pythonwindows-10python-imaging-libraryscreenshot

PIL module save function on Win10 only return black image


I am having issue with saving screenshot via PIL.Image.save function on Windows 10. PIL.Image.show() function works fine and represents screenshot as expected but save function save image as fully black picture. Is it possible somehow to save picture normally with PIL inner functions?

from PIL import ImageGrab
import os
from PIL import Image

path='C:\ProgramData\'

player_id='1'
player_name='player'
_format='PNG'

pic_name = player_id + '.' + _format
screen = Image.Image
screen = Image.new("RGB", (1280, 720), 0)
def make_screen_shot():
    try:
        screen = ImageGrab.grab()
        screen.show()          
    except IOError:
        return False
    else:
        return True

def save_pic():
    pic_name = player_id + '.' + _format
    try:

        screen.save(os.path.join(path, pic_name), _format)
    except IOError:
        return False
    else:
        return True
make_screen_shot()
save_pic()

Solution

  • The problem here is that you are dealing with two functions.
    So your functions creating local variables.
    Therefor your "screen" is empty in the save function -> will be black.

    For reference: Python Global, Local and Nonlocal variables

    from PIL import ImageGrab
    import os
    from PIL import Image
    
    path='C:/ProgramData/'
    
    player_id='1'
    player_name='player'
    _format='PNG'
    
    pic_name = player_id + '.' + _format
    screen = Image.Image
    screen = Image.new("RGB", (1280, 720), 0)
    def make_screen_shot():
        try:
            screen = ImageGrab.grab()
            screen.show()
            save_pic(screen)         
        except IOError:
            return False
        else:
            return True
    
    def save_pic(image):
        screen = image
        pic_name = player_id + '.' + _format
        try:
    
            screen.save("test.png") #here you can use your save function just renamed for testing
        except IOError:
            return False
        else:
            return True
    make_screen_shot()
    

    This will work :) Also you can create global variable or save it above directly.