Example #1
0
def main():
    # Make sure we have enough stuff
    if len(sys.argv) < 3:
        print('Usage:')
        print('    ./gif2blit.py <gif> <output_dir>')
        sys.exit(0)

    # Need to make the QApp first
    app = QApplication(sys.argv)

    # Assume that all of the input is valid
    gifName = sys.argv[1]
    outputDirName = sys.argv[2]

    # Open of the animated GIF
    gif = QMovie(gifName)

    # Make the directory if it doesn't exist
    if not os.path.exists(outputDirName):
        os.makedirs(outputDirName)

    # Build the strucutres, get some data
    xsheet = XSheet(fps=50)
    anim = Animation(xsheet=xsheet,
                     name=os.path.basename(gifName),
                     created=time.ctime())
    frameCount = gif.frameCount()
    msDelayPerFrame = 1000 // xsheet.fps()
    timingOff = False
    filename = ''

    # Start the loop, but just look at the first frame so we can get the size
    gif.jumpToNextFrame()
    anim.setSize(gif.currentImage().size())

    # Add all of the frames together
    for i in range(0, frameCount):
        # Make the new frame and add it
        f = Frame()
        c = Cel(gif.currentImage().convertToFormat(
            QImage.Format_ARGB32_Premultiplied))
        f.setHold(gif.nextFrameDelay() // msDelayPerFrame)
        f.addCel(c)
        xsheet.addFrame(f)

        # Save images as we go along
        try:
            filename = os.path.join(outputDirName, '%s.png' % c.UUID())
            c.image().save(filename)
            print(filename)
        except:
            print('There was an error in trying to save a Cel to:\n  %s' %
                  filename)
            sys.exit(1)

        # Checking for not so good shifts in timing
        if (gif.nextFrameDelay() % msDelayPerFrame) != 0:
            timingOff = True

        # Dump it
        gif.jumpToNextFrame()

    # And save the JSON, then we're done
    try:
        filename = os.path.join(outputDirName, 'sequence.json')
        f = open(filename, 'w')
        f.write(structToJSON(animationToJSONStruct(anim)))
        f.close()
    except:
        print('There was an error in tyring to save the JSON file to:\n  %s' %
              filename)
        sys.exit(1)

    # Metrics:
    print('Converted a GIF with %i frames.' % xsheet.numFrames())
    if timingOff:
        print(
            'Because of the set FPS and the delay of the frames in the GIF, the timing might be off in the converted animation.'
        )