"SystemError: tile cannot extend outside image" in PIL during save image

With reference to the comments, the error occurred due to improper passing of the coordinates to PIL's crop() function.

As mentioned in the documentation, the function returns an image having taken in a tuple of four (x, y, width and height).

In the given text file the y coordinate is mentioned in the first column and x coordinate in the second column. The crop() function however accepts the value of x coordinate as the first parameter and the y coordinate as the second parameter.

The same applies for OpenCV as well

Here is ANOTHER POST regarding the same.


In my case the issue was that I was specifying start and end coordinates where the start X and start Y were not always less than the end X and Y. You cannot do this.

For example,

Start: (0, 50) End: (50, 0)

These coordinates make sense to me, but should actually be specified as:

Start: (0, 0) End: (50, 50)

Visually the same rectangle, but the latter is required for Pillow to crop.


The mentioned way on the internet is like this:

imageScreenshot.crop((x, y, width, height))

But the correct way is this:

imageScreenshot.crop((x, y, x + width, y + height))

Meaning that you should add the x to the width and y to the height.
This is a simple example (driver is for python selenium):

def screenShotPart(x, y, width, height) -> str:
    screenshotBytes = driver.get_screenshot_as_png()
    imageScreenshot = Image.open(BytesIO(screenshotBytes))
    imageScreenshot = imageScreenshot.crop((x, y, x + width, y + height))
    imagePath = pathPrefix + "_____temp_" + str(time.time()).replace(".", "") + ".png"
    imageScreenshot.save(imagePath)

Hope it helps.