상세 컨텐츠

본문 제목

How to Convert MP4 to GIF in Python using Moviepy

Coding/Python

by 세미531 2023. 5. 6. 17:22

본문

728x90

In this tutorial, we will demonstrate how to convert an MP4 video file into a GIF animation using the moviepy library in Python. Moviepy is a powerful library for video editing that allows you to perform various operations on video files.

 

Step 1: Install the moviepy library
First, you need to install the moviepy library using pip. Open your terminal or command prompt and run the following command:

pip install moviepy

 

 

Step 2: Create a Python script for the conversion
Once the library is installed, you can create a Python script to perform the conversion. Here's the code to convert an MP4 file to a GIF file:

 

from moviepy.editor import *

def convert_mp4_to_gif(input_file, output_file, start_time=0, end_time=None, resize_factor=1.0):
    # Load the video file
    video = VideoFileClip(input_file)

    # Set the start and end time if provided
    if end_time is not None:
        video = video.subclip(start_time, end_time)

    # Resize the video if a resize factor is provided
    if resize_factor != 1.0:
        video = video.resize(resize_factor)

    # Write the video as a GIF file
    video.write_gif(output_file, fps=15, program='ffmpeg')

if __name__ == "__main__":
    input_file = "path/to/your/input/video.mp4"
    output_file = "path/to/your/output/animation.gif"

    # Optional parameters
    start_time = 0  # Start time in seconds, default is 0
    end_time = None  # End time in seconds, default is None (entire video)
    resize_factor = 0.5  # Resize factor, default is 1.0 (no resizing)

    convert_mp4_to_gif(input_file, output_file, start_time, end_time, resize_factor)

Replace the input_file and output_file variables with the appropriate file paths for your input MP4 and output GIF files.

Step 3: Run the script
To convert your MP4 video file to a GIF animation, simply run the Python script you created in the previous step. The script will load the MP4 video, create a subclip if start and end times are provided, resize the video based on the resize factor, and then write the output as a GIF file with a frame rate of 15 frames per second.

Conclusion:
In this tutorial, we have shown you how to convert an MP4 video file into a GIF animation using the moviepy library in Python. You can now easily convert your videos to GIF animations to use in various projects or share on social media.

 

 

 

728x90

관련글 더보기

댓글 영역