I am trying to convert a gif, first crop it then convert it into a gif which only loops once. It loops only once when I use Microsoft “Photo” app. However when on a html page it loops twice.
I’ve tried changing loop = 0
, but it makes the loop become infinite.
This is the code I am using:
from PIL import Image, ImageSequence
input_gif = "input.gif"
output_gif = "output.gif"
crop_box = (0, 0, 300, 500) # (left, upper, right, lower)
with Image.open(input_gif) as gif:
frames = []
for frame in ImageSequence.Iterator(gif):
cropped_frame = frame.crop(crop_box)
frames.append(cropped_frame)
frames[0].save(
output_gif,
save_all=True,
append_images=frames[1:],
loop=1,
duration=gif.info.get("duration", 100),
)
print("GIF cropped and saved successfully!")