Search code examples
pythonmathsizemoviepy

How can i resize image in moviepy so that it perfectly fits in 1980x1080?


So I'm trying to resize an image and maintain its ratio so that it perfectly fits in 1980x1080 in the moviepy library.

Currently, I'm doing this with a function like this:

def FitClip(size):
    
    #size is basicly clip.size
    clipRes = size
    #print(size)

    v = ''
    
    if clipRes[0] >= clipRes[1]:
        toresize = 1980
        v = 'h'
    else:
        toresize = 1080
        v = 'v'
    return [toresize, v]

and I'm calling it like this:

def generate_clip_var(clip_name, start_time):
    clip_audio = AudioFileClip(f"out/{clip_name}.mp3").set_start(start_time + 2)
    clip_video = ImageClip(f"out/{clip_name}.jpg").set_duration(1).set_start(start_time)

    if FitClip(clip_video.size)[1] == 'v':
        clip_video = ImageClip(f"out/{clip_name}.jpg").set_duration(clip_audio.duration + 1).set_position("center").set_audio(clip_audio).resize(height = FitClip(clip_video.size)[0]).set_start(start_time)
    else:
        clip_video = ImageClip(f"out/{clip_name}.jpg").set_duration(clip_audio.duration + 1).set_position("center").set_audio(clip_audio).resize(width = FitClip(clip_video.size)[0]).set_start(start_time)

    return [clip_audio, clip_video]

My problem is that whenever image is too small or too big it just goes outside bounds.

help


Solution

  • You could try the moviepy native function resize():

    from moviepy.video.fx.resize import resize
    
    def generate_clip_var(clip_name, start_time):
        clip_audio = AudioFileClip(f"out/{clip_name}.mp3").set_start(start_time + 2)
        clip_video = ImageClip(f"out/{clip_name}.jpg").set_duration(1).set_start(start_time)
    
        # Resize the clip_video object to fit within a 1980x1080 frame while maintaining its aspect ratio
        clip_video = resize(clip_video, width=1980, height=1080)
    
        # Set the duration and audio of the resized clip_video object
        clip_video = clip_video.set_duration(clip_audio.duration + 1).set_position("center").set_audio(clip_audio).set_start(start_time)
    
        return [clip_audio, clip_video]