Use the Pillow module for Python to "roll" images horizontally or vertically. When an image is rolled, it is shifted in some direction. The part of the image that would be lost as a result of that shift is added onto the opposite side of the image.
Last active
May 8, 2025 13:06
-
-
Save sloanlance/74ec4196da65295e1ecbaf0a139ff792 to your computer and use it in GitHub Desktop.
Using Pillow to roll images horizontally and vertically.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
roll.py | |
Inspired by an example from Pillow documentation: | |
https://pillow.readthedocs.io/en/stable/handbook/tutorial.html#:~:text=Rolling%20an%20image,))%0A%0A%20%20%20%20return%20im | |
""" | |
from PIL import Image | |
def roll(im: Image.Image, vector: (int, int)) -> Image.Image: | |
"""Roll an image in a given direction.""" | |
if vector[0] != 0: | |
im = roll_horizontal(im, vector[0]) | |
if vector[1] != 0: | |
im = roll_vertical(im, vector[1]) | |
return im | |
def roll_horizontal(im: Image.Image, delta: int) -> Image.Image: | |
"""Roll an image horizontally.""" | |
xsize, ysize = im.size | |
delta = delta % xsize | |
if delta == 0: | |
return im | |
part1 = im.crop((0, 0, delta, ysize)) | |
part2 = im.crop((delta, 0, xsize, ysize)) | |
im.paste(part1, (xsize - delta, 0, xsize, ysize)) | |
im.paste(part2, (0, 0, xsize - delta, ysize)) | |
return im | |
def roll_vertical(im: Image.Image, delta: int) -> Image.Image: | |
"""Roll an image horizontally.""" | |
xsize, ysize = im.size | |
delta = delta % ysize | |
if delta == 0: | |
return im | |
nim = im.copy() # Important: copy to avoid modifying the original | |
part1 = nim.crop((0, 0, xsize, delta)) | |
part2 = nim.crop((0, delta, xsize, ysize)) | |
nim.paste(part1, (0, ysize - delta, xsize, ysize)) | |
nim.paste(part2, (0, 0, xsize, ysize - delta)) | |
return nim | |
try: | |
image = Image.open('icon1024x1024.png') | |
# Roll 800 pixels to the right | |
rolled_image_horizontal = roll(image, (800, 0)) | |
rolled_image_horizontal.save('rolled_image_horizontal.png') | |
# Roll 500 pixels down | |
rolled_image_vertical = roll(image, (0, 500)) | |
rolled_image_vertical.save('rolled_example_vertical.png') | |
# Roll 800 pixels left and 625 up | |
rolled_image_diagonal = roll(image, (-800, -625)) | |
rolled_image_diagonal.save('rolled_image_diagonal.png') | |
except FileNotFoundError: | |
print('Error: Image file not found.') | |
except Exception as e: | |
print(f'An error occurred: {e}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment