How to Create Animated Gifs with Python
python·@makerhacks·
0.000 HBDHow to Create Animated Gifs with Python
 Have you wondered how you can make your own gifs? Now, certainly, this is not the easiest way, but it is a fun project for learning, and heck, it might come in useful one day ;) [You may remember that I already covered how to create a movie from time-lapse photographs](https://steemit.com/linux/@makerhacks/converting-videos-and-creating-timelapse-from-photographs-in-linux), this is similar and takes the technique a couple of steps further. ### Code #### [Full Code Gist Here](https://gist.github.com/omiq/159e042339d3d27f2e6a490924d881fd) First, we need some modules. OS and Shutil are for shell operations, because we need to call tools and create/delete folders. ``` import os import shutil from PIL import ImageFont from PIL import Image from PIL import ImageDraw ``` Next, we create the folder if it does not already exist, nuking the contents if it does. We also create our image, loading in a background first. ``` if os.path.exists('frames'): shutil.rmtree('frames') os.mkdir('frames') img_background = Image.open('background.png') img = Image.new("RGBA", img_background.size, (0, 0, 0, 255)) ``` We need three colours, and a nice font. ``` x = 10 y = 10 silver = (100, 100, 100, 255) purple = (100, 0, 200, 255) white = (255, 255, 255, 255) text = '''Boing!''' font = ImageFont.truetype("/home/chrisg/Ubuntu-B.ttf", 75) draw = ImageDraw.Draw(img) ``` Now we create the frames of animation, 24 frames for 1 second. All I am doing here is adding text to each frame in a different location, you can get wild in yours! ``` for N in range(0, 24): y += N img.paste(img_background, (0, 0)) draw.text((x+4, y+4), text, purple, font=font) draw.text((x+2, y+2), text, silver, font=font) draw.text((x, y), text, white, font=font) img.save("./frames/{}.png".format(str(N).zfill(3))) ``` All that is left is to generate an AVI then convert to gif. For higher quality we can come back and [optimize the palette](https://steemit.com/programming/@makerhacks/how-to-get-higher-quality-gifs-with-ffmpeg), but for simplicity this is sufficient for now! ``` os.system('ffmpeg -framerate 24 -i frames/%03d.png -c:v ffv1 -r 24 -y out.avi') os.system('ffmpeg -y -i out.avi out.gif') shutil.rmtree('frames') ``` <hr> https://cdn.steemitimages.com/0x0/https://cdn.discordapp.com/attachments/383256479056134146/446022370608676864/makerhacks.png
👍 makerhacks, detlef-s, xerox-bru, macmaniac77, ubik, beajinsu, bat-junior, sajib7, snowflake, theuxyeti, theadmiral0, riezaldi, inceptionally, share4every1, taukproung85, tpvoter1, telos, sylph, flurgx, upbloke, mikepm74, kryptograf, ccsbot, themonetaryfew, mione, alnedkov, dianargenti, maurocostarica, errymil, khamen, dbwitty, shrazi, bestlife, muhammadadil, simi, k3nb0b, beauknows, thi-js, caroliny, jguzman394, citizendog, christianytony, mrsadman, mystifact, jrhughes, dontbenormal, snoe860, deluge, w-inv, hannesl, wasimk87, mackcom, arqetype, ccoin, sidwaterman, fede93g, coar, carmucha60, henryn2020, melek, nataliechickee, samstickkz, steemitcitizen, greyman, patriot, krisii, steem-gaming, xevil, valderrama, prashant, fat-elvis, buildteam, glitterbooster, bunnypunia, salas, engramanullah, initforthemoney, malikidrees, hamidaansary, flameburst, vishalsingh4997, luciamuresan, annadoll, ramsteem, hemanthoj, seaofhappy, adamdonmez, pillsjee, yatri, wond2006, roberta92, rampagejr, taxguy, preshey, jr006, ioba, motherofalegend, rubaet, storywriter, robbie5, nathanieloamhen, jutdagut, murad06, nsiman, talivet, gnomicrules, favoured001, dshelton32, majorsteemian, simplewole, emmywell, develcuy, transcendingman, dailygiveaway, rawpride, sbi3, dmxmaster, geekpowered, warjar, jcsteem, nolnocluap, raili, lisaocampo, techblogger, steemnsfw, xglider, gyanibilli, ninaflowers, rocketgyi, melbookermusic, fakhre, lixing, cryptoflower23, davidcross, michaeljpsalazar, krishankumar, elbreeder, dexterslab, zakariahosen, islamic1, matiasmenarguez, ryanhagerty, niko3d, skvyrla, libertylemon, steemwildboy, arzon-cnaster, mikromixstudio, meher04, bidnat, olezoom, libert, dexter-stoner, thepsychguide, olesia, rkaz, whiteblood, shae-meyer, coffeelovers, steemitbc, cocinecomounchef, tonygreene113, mayankverma, nirgf, nikonmarshall, gooddeeds, celioeguga, talhadogan, beauty.world, brwaves, therusticvegan, udgu, swt3df1, mindscapephotos, vargart, talentscout, farhankhann, cryptoissweet, christianvas, naijawhale, faisal1650, emmanuelzod, xxxkoenigxxx, voinnov111, alexander11, germanaure, jmcgready, steeming4, seongbuk, lamex, dreamzchm, bachone, catchup, walidsalah, thaiprincess, cryptonewsdesk, wamsverrucko, sharif24, myperfectblog, ygmraykt, sam1210, afrasyabmaier, divinitysa, irishgirl, trasric, khinzawlatt, jchauhan, rusdiana, hightea, cryptovate, taiki9121, justlibby, steemitshopaus, nelufareasmin, furn01, chryzed, ligayagardener, kentzz001, cryptodj99, ivkaptuk, arorapuneet, tagsplanet, markperandin, klinckify, keshawn, creativebuilds, kingjan, upgoat, click3rs, joanderit, amanpathak, klizo, rexcaelestis, m3mt, starcontract, andii, molikhatun, jey-blue, hariman, grupobimbyaa, dandan2013, photosdaily, funstuff, whatstuff, synergysteem, netscape101, nafisah, letsawesome, themarkymark, pynchon,