Skip to content

Instantly share code, notes, and snippets.

@prophetgoddess
Created October 28, 2017 17:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prophetgoddess/ae872963f731b020861e55698944c3e8 to your computer and use it in GitHub Desktop.
Save prophetgoddess/ae872963f731b020861e55698944c3e8 to your computer and use it in GitHub Desktop.
python script to glitch gifs
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Copyright (c) 2017 Emma Lugo
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
# A script to extract image frames from a gif, glitch them with the jpglitch library, and then recompile them into a new gif.
# Made with help from this gist: https://gist.github.com/BigglesZX/4016539
# Requires: imageio (https://imageio.github.io/), Pillow (https://python-pillow.org/), jpglitch (https://github.com/Kareeeeem/jpglitch)
import os, imageio, shutil, random, click, time
from PIL import Image
INPUT_DIR = "tmp/input"
OUTPUT_DIR = "tmp/output"
MIN_SEED = 0
MAX_SEED = 99
MIN_AMOUNT = 0
MAX_AMOUNT = 99
def analyze_image(path):
im = Image.open(path)
results = {
'size': im.size,
'mode': 'full',
}
try:
while True:
if im.tile:
tile = im.tile[0]
update_region = tile[1]
update_region_dimensions = update_region[2:]
if update_region_dimensions != im.size:
results['mode'] = 'partial'
break
im.seek(im.tell() + 1)
except EOFError:
pass
return results
def process_image(path, miniter, maxiter):
mode = analyze_image(path)['mode']
im = Image.open(path)
i = 0
p = im.getpalette()
last_frame = im.convert('RGBA')
amount = random.randint(MIN_AMOUNT, MAX_AMOUNT)
try:
while True:
print("saving {} ({}) frame {}, {} {}".format(path, mode, i, im.size, im.tile))
if not im.getpalette():
im.putpalette(p)
new_frame = Image.new('RGB', im.size)
if mode == 'partial':
new_frame.paste(last_frame)
frame_path = '{}/{}-{}.jpg'.format(INPUT_DIR, ''.join(os.path.basename(path).split('.')[:-1]), i)
glitched_path = '{}/{}-{}-glitched.jpg'.format(OUTPUT_DIR, ''.join(os.path.basename(path).split('.')[:-1]), i)
new_frame.paste(im, (0,0), im.convert('RGBA'))
new_frame.save(frame_path, 'JPEG')
command = 'jpglitch {} -a {} -i {} -s {} -o {}'.format(
frame_path,
amount,
random.randint(miniter, maxiter),
random.randint(MIN_SEED, MAX_SEED),
glitched_path)
os.system(command)
i += 1
last_frame = new_frame
im.seek(im.tell() + 1)
except EOFError:
pass
@click.command()
@click.option('--gif', default="image.gif", help="The gif you want to glitch.")
@click.option('--maxiter', default=20, help="maximum number of iterations fed to jpglitch")
@click.option('--miniter', default=0, help="minimum number of iterations fed to jpglitch")
def glitch_gif(gif, maxiter, miniter):
os.makedirs(INPUT_DIR)
os.makedirs(OUTPUT_DIR)
process_image(gif, miniter, maxiter)
files = os.listdir(OUTPUT_DIR)
frames = []
for file in files:
frames.append(imageio.imread(os.path.join(OUTPUT_DIR, file)))
filename = 'glitched-{}.gif'.format(int(time.time()))
imageio.mimsave(filename, frames)
print("Done! {}".format(filename))
shutil.rmtree('tmp/')
if __name__ == '__main__':
glitch_gif()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment