Last active
November 8, 2021 19:34
-
-
Save mjdargen/a159df8e435b5838d7af69ed2c63edc0 to your computer and use it in GitHub Desktop.
converts a gif into a sprite sheet. handles transparency.
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
import os | |
from PIL import Image | |
def split(gif): | |
im = Image.open(gif) | |
for frame in range(im.n_frames): | |
im.seek(frame) | |
# convert transparent background to black | |
bg_colour = (0, 0, 0) | |
temp = im.convert("RGBA") | |
if temp.mode in ('RGBA', 'LA'): | |
background = Image.new(temp.mode[:-1], im.size, bg_colour) | |
background.paste(temp, temp.split()[-1]) # omit transparency | |
print(f'Saving frame {frame}') | |
background.convert('RGB').save(f'./{gif.split(".")[0]}{frame}.jpg') | |
def combine(gif): | |
# remove old file | |
try: | |
os.remove(f'./{gif.split(".")[0]}.bmp') | |
except OSError: | |
pass | |
# retrieve all relevant bitmaps | |
files = os.listdir('.') | |
files = [f for f in files if gif.split(".")[0] in f and '.jpg' in f] | |
# set up initial image with first frame | |
first = Image.open(files[0]).convert('RGBA') | |
sheet = Image.new('RGB', (first.width, first.height)) | |
sheet.paste(first, (0, 0)) | |
sheet.save(f'./{gif.split(".")[0]}.bmp', 'BMP') | |
# continue for all subsequent frames | |
for file in files[1:]: | |
im = Image.open(file).convert('RGBA') | |
sheet = Image.open(f'./{gif.split(".")[0]}.bmp').convert('RGBA') | |
combined = Image.new('RGB', (sheet.width, sheet.height + im.height)) | |
combined.paste(sheet, (0, 0)) | |
combined.paste(im, (0, sheet.height)) | |
combined.save(f'./{gif.split(".")[0]}.bmp', 'BMP') | |
for file in files: | |
try: | |
os.remove(f'./{file}') | |
except OSError: | |
pass | |
if __name__ == '__main__': | |
filename = 'ball.gif' | |
split(filename) | |
combine(filename) |
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
from PIL import Image | |
# converts .png horizontal sprite sheet to .bpm vertical sprite sheet | |
def convert(png): | |
# open horizontal sprite sheet and count number of frames | |
hor = Image.open(png) | |
frames = hor.width // 64 | |
# create new vertical sprite sheet, crop and copy frame by frame | |
ver = Image.new('RGB', (64, hor.height * frames)) | |
for frame in range(frames): | |
ver.paste(hor.crop((frame*64, 0, (frame+1)*64, 32)), (0, frame*32)) | |
# save new sprite sheet | |
ver.save(f'./{png.split(".")[0]}.bmp') | |
if __name__ == '__main__': | |
filename = 'myball.png' | |
convert(filename) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment