CONVERT MP4 TO GIF HÀNG LOẠT BẰNG PYTHON + FFMPEG

OneHub

Staff member
Mr Boss
🎬 CONVERT MP4 TO GIF HÀNG LOẠT BẰNG PYTHON + FFMPEG

⚡ Nhanh • Đơn giản • Tự động • Dễ sử dụng



📌 Chức năng

Đoạn code Python này giúp bạn chuyển đổi hàng loạt video MP4 thành ảnh GIF chỉ với một lần chạy.

Một số tính năng chính:


  • []🎞️ Tự động tìm tất cả file .mp4 trong thư mục.
    [
    ]🔄 Chuyển hàng loạt MP4 → GIF.
    []📐 Tự giữ đúng tỷ lệ video khi resize.
    [
    ]⚙️ Cho phép tùy chỉnh FPS và chiều rộng GIF.
    []🔁 GIF tự động phát lặp vô hạn.
    [
    ]♻️ Tự ghi đè GIF cũ khi chạy lại.
    []🛡️ Một video lỗi không làm dừng toàn bộ quá trình.
    [
    ]📂 Tự tạo thư mục videogif.

Rất phù hợp để tạo GIF demo website, addon XenForo, giao diện, hướng dẫn thao tác hoặc giới thiệu tính năng sản phẩm.



🛠️ Chuẩn bị

1. Cài Python

Kiểm tra Python bằng CMD:

Code:
python --version

2. Cài FFmpeg

Sau khi cài FFmpeg và thêm vào PATH, kiểm tra:

Code:
ffmpeg -version

3. Cài thư viện ffmpeg-python

Code:
pip install ffmpeg-python

Nếu lệnh pip không hoạt động:

Code:
py -m pip install ffmpeg-python

[NOTE]
Package cần cài có tên ffmpeg-python, nhưng trong Python vẫn sử dụng import ffmpeg.
[/NOTE]



🚀 Cách sử dụng

Bước 1: Lưu code bên dưới thành:

Code:
video_to_gif.py

Bước 2: Chạy file một lần hoặc tự tạo thư mục video.

Bước 3: Copy các video MP4 cần chuyển vào:

Code:
video/

Ví dụ:

Code:
video/
├── demo.mp4
├── addon.mp4
└── tutorial.mp4

Bước 4: Chạy:

Code:
python video_to_gif.py

Hoặc trên Windows:

Code:
py video_to_gif.py

Bước 5: GIF sau khi hoàn thành sẽ tự động xuất hiện trong:

Code:
gif/
├── demo.gif
├── addon.gif
└── tutorial.gif



⚙️ Tùy chỉnh chất lượng GIF

Bạn có thể chỉnh tại cuối code:

Code:
converter = VideoToGifConverter(
source_dir="video",
target_dir="gif",
frame_rate=2,
width=640
)

Trong đó:


  • []source_dir — Thư mục chứa video.
    [
    ]target_dir — Thư mục lưu GIF.
    []frame_rate — Số khung hình/giây.
    [
    ]width — Chiều rộng GIF theo pixel.

Gợi ý FPS:

Code:
2 FPS = GIF nhẹ, chuyển động cơ bản
5 FPS = Cân bằng dung lượng/chất lượng
10 FPS = Chuyển động khá mượt
15 FPS = Mượt hơn nhưng dung lượng lớn

Đối với GIF demo trên website/forum, có thể bắt đầu với:

Code:
frame_rate=5
width=640

rồi tăng hoặc giảm tùy nhu cầu.



💻 CODE ĐẦY ĐỦ

Python:
import os
import ffmpeg

class VideoToGifConverter:
def [B]init[/B](
self,
source_dir="video",
target_dir="gif",
frame_rate=2,
width=640
):
"""
Chuyển toàn bộ file MP4 trong source_dir thành GIF.

    source_dir : Thư mục chứa video MP4
    target_dir : Thư mục lưu GIF
    frame_rate : Số khung hình mỗi giây
    width      : Chiều rộng GIF
    """

    self.source_dir = source_dir
    self.target_dir = target_dir
    self.frame_rate = frame_rate
    self.width = width

    # Tự động tạo thư mục nếu chưa tồn tại
    os.makedirs(self.source_dir, exist_ok=True)
    os.makedirs(self.target_dir, exist_ok=True)

def get_video_files(self):
    """Lấy danh sách tất cả file MP4."""
    return [
        file_name
        for file_name in os.listdir(self.source_dir)
        if file_name.lower().endswith(".mp4")
    ]

def convert_video(self, video_file):
    """Chuyển một video MP4 thành GIF."""

    base_name = os.path.splitext(video_file)[0]
    gif_file_name = base_name + ".gif"

    input_path = os.path.join(self.source_dir, video_file)
    output_path = os.path.join(self.target_dir, gif_file_name)

    print(f"Đang chuyển: {video_file}")

    try:
        stream = ffmpeg.input(input_path)

        # Điều chỉnh FPS
        stream = stream.filter(
            "fps",
            fps=self.frame_rate,
            round="up"
        )

        # Resize và giữ nguyên tỷ lệ video
        stream = stream.filter(
            "scale",
            self.width,
            -1,
            flags="lanczos"
        )

        stream = ffmpeg.output(
            stream,
            output_path,
            loop=0
        )

        # Cho phép ghi đè file GIF cũ
        ffmpeg.run(
            stream,
            overwrite_output=True,
            quiet=True
        )

        print(f"Hoàn thành: {output_path}")

    except ffmpeg.Error as error:
        print(f"Lỗi khi chuyển {video_file}")

        if error.stderr:
            try:
                print(error.stderr.decode("utf-8"))
            except Exception:
                pass

    except Exception as error:
        print(f"Lỗi không xác định: {error}")

def convert_videos_to_gif(self):
    """Chuyển tất cả MP4 trong thư mục."""

    video_files = self.get_video_files()

    if not video_files:
        print(
            f"Không tìm thấy file MP4 trong thư mục: "
            f"{self.source_dir}"
        )
        return

    print(f"Tìm thấy {len(video_files)} video.")
    print("-" * 50)

    for video_file in video_files:
        self.convert_video(video_file)

    print("-" * 50)
    print("Đã xử lý xong tất cả video.")

def main():
converter = VideoToGifConverter(
source_dir="video",
target_dir="gif",
frame_rate=2,
width=640
)

converter.convert_videos_to_gif()
if [B]name[/B] == "[B]main[/B]":
main()



💡 Ví dụ

Bạn có video:

Code:
video/demo.mp4

Chạy:

Code:
py video_to_gif.py

Chương trình sẽ tạo:

Code:
gif/demo.gif

GIF được resize về chiều rộng 640px, tự giữ tỷ lệ và tự động phát lặp.

[NOTE]
💡 Mẹo: GIF có thể lớn hơn MP4 khá nhiều. Nếu chỉ dùng để demo trên XenForo, nên sử dụng chiều rộng khoảng 500–640px5–10 FPS để cân bằng giữa độ mượt và dung lượng.
[/NOTE]

🎉 Chỉ cần bỏ MP4 vào thư mục → chạy Python → nhận GIF!
 
Back
Top