how to code a gif that gradually transform one picture into another



  • how to code a gif that gradually transform one picture into another



  • Hi, hope this helps:

    # Get your gif routes
    gifsFolder = '.' # Your gifs directory
    gifs = ['gif1.gif', 'gif2.gif'] # These are the files I'll use
    gifPaths = [f'{gifsFolder}/{gif}' for gif in gifs] # Create the paths for your with string formattingx
    
    # Create a function to interpolate between gifs
    
    def scaleFactor(path, pageNumber, canvasSize): # Get a scale factor to match the canvas size you want
        gifw, gifh = imageSize(path, pageNumber=pageNumber)
        factorMeasure = gifw
        if gifw > gifh:
            factorMeasure = gifh
        return  canvasSize / factorMeasure
    
    def gifTransition(path1, path2):
        # Canvas and images dimensions
        w, h = 200, 200 # Canvas size
        
        # Define your frames
        introFrames = numberOfPages(path1)
        endingFrames = numberOfPages(path2)
        crossfadeFrames = 12 # Change this value for a longer transition
        totalFrames = int(
            (introFrames - crossfadeFrames/2)+(endingFrames - crossfadeFrames/2)
            ) # Get the total frames by merging the crossfade in the middle 
        
        # Make a loop for the animation
        gif1Frames, gif2Frames = 0, 0
        gif1alpha, gif2alpha = 1, 0
        for frame in range(1, totalFrames+1):
            newPage(w, h)
            fill(1)
            rect(0, 0, w, h)
            with savedState():
                scale(scaleFactor(path1, gif1Frames, w))
                image(path1, (0, 0), pageNumber=gif1Frames, alpha=gif1alpha)
            if gif1Frames < introFrames:
                gif1Frames += 1
            if frame > introFrames - crossfadeFrames/2: # Run the second gif
                with savedState():
                    scale(scaleFactor(path2, gif2Frames, w))
                    image(path2, (0, 0), pageNumber=gif2Frames, alpha=gif2alpha)
                gif2Frames += 1
                if gif1alpha >= 0 or gif2alpha <= 1: # Crossfade transparency
                    gif1alpha -= 1 / crossfadeFrames
                    gif2alpha += 1 / crossfadeFrames
                
    gifTransition(gifPaths[0], gifPaths[1]) # Call the function
    saveImage('~/Desktop/gifCrossfade.gif') # Save your gif