Turn a Long Image into a GIF with Python’s PIL: Step‑by‑Step Guide
Learn how to split a lengthy image into equal‑height segments using Python’s PIL library and then recombine those pieces into an animated GIF, complete with code examples, command‑line usage, and tips for handling watermarks and unwanted overlays.
In anticipation of the “network Valentine’s Day” (520), the author shares a light‑hearted view before diving into a practical Python tutorial.
Splitting a Long Image
The long picture consists of 16 dialogue frames. By cropping the image into equal‑height slices using Image.crop(), each slice can be saved as a separate PNG. The cropping box is defined as (left, upper, right, lower) coordinates.
import os
from PIL import Image
def split_image(file, split_times):
path, filename = os.path.split(file)
os.chdir(path)
try:
os.mkdir('pictures')
except FileExistsError:
pass
img = Image.open(filename)
width, height = img.size
per_height = height / split_times
for pictureNumber in range(split_times):
_cropBox = (0, per_height * pictureNumber, width * 0.8, per_height * (pictureNumber + 1))
picture = img.crop(_cropBox)
picture_name = os.path.join(path, 'pictures', "%d.png" % pictureNumber)
picture.save(picture_name)
split_image("C:\\Users\\Administrator\\Downloads\\520.jpg", 16)The width is reduced to 80 % to exclude watermarks and the “Tencent Video” logo.
Combining the Slices into a GIF
After obtaining the 16 PNG files, they are merged into an animated GIF using the duration parameter of Image.save().
import argparse
from PIL import Image
import os
class SplitLongPicture:
def __init__(self):
self.dirName = os.path.split(os.path.abspath(__file__))[0]
self.ImagePath = args.ImagePath
self.SplitTimes = args.SplitTimes
self.SwitchingTime = args.SwitchingTime
self.Path, self.File = os.path.split(self.ImagePath)
self.Image = self.check_image_file()
self.pictureList = []
def check_image_file(self):
_imageType = ['.jpg', '.png', '.bmp']
if not os.path.isfile(self.ImagePath):
raise IOError("Please check the image path", self.ImagePath)
elif os.path.splitext(self.File)[1].lower() not in _imageType:
raise TypeError("Please select a supported image type", _imageType)
else:
return Image.open(self.ImagePath)
def split_image(self):
os.chdir(self.Path)
try:
os.makedirs('pictures')
except FileExistsError:
pass
width, height = self.Image.size
_unitHeight = height / self.SplitTimes
for pictureNumber in range(self.SplitTimes):
_cropBox = (0, _unitHeight * pictureNumber, width * 0.8, _unitHeight * (pictureNumber + 1))
_unitPicture = self.Image.crop(_cropBox)
_pictureName = os.path.join(self.Path, 'pictures', "%d.png" % pictureNumber)
self.pictureList.append(_pictureName)
_unitPicture.save(_pictureName)
def composite_gif(self):
images = []
im = Image.open(self.pictureList[0])
for file in self.pictureList[1:]:
images.append(Image.open(file))
gifName = os.path.join(self.Path, "result.gif")
im.save(gifName, save_all=True, loop=True, append_images=images, duration=self.SwitchingTime * 1000)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--ImagePath', help="Path to the image to split")
parser.add_argument('-t', '--SplitTimes', type=int, help="Number of slices")
parser.add_argument('-s', '--SwitchingTime', type=float, help="Frame duration in seconds")
args = parser.parse_args()
if None in args.__dict__.values():
parser.print_help()
else:
Main = SplitLongPicture()
Main.split_image()
Main.composite_gif()Run the script with:
python D:\SplitLongPicture.py -p C:\Users\Administrator\Downloads\520.jpg -t 16 -s 1.25The resulting result.gif animates the original long image, providing a more engaging way to view the content.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
