Posting videos to note is a hassle, so I made a tool to convert MP4 to GIF
Introduction
Good evening. This is Hottarita. I've been posting about Micro:bit lately, and I find myself wanting to upload videos of it in action.
(This isn't limited to Micro:bit; it's the same for other DIY projects, too...)
But... isn't it a pain to post videos on note?
I might just be unaware, but I assume you have to embed a link from YouTube or Vimeo, right?
I felt that uploading just to post on note was quite a chore, so I wrote a program to convert videos to GIFs for note posts—it wasn't particularly difficult. (I know there are services on the web that do this. But I don't really like using those kinds of sites, so I made my own.)
Since I intended for only myself to use it this time, I had Claude-Code build it while I was tinkering with the micro:bit with my son. It's a Python program.
I think anyone who basically touches Python could write this themselves without me posting the code, but I'll include it anyway.
I'll also provide the program so it can be used in Google Colab. I hope it's useful to someone.
(How to use Google Colab should come up if you Google it, but if this article gets read, there might be a need for it, so I'll write a manual article.)
Note: However, I realized after making it that if you need audio, it's tough with a GIF, so you end up having to upload to YouTube if you need sound, haha. I'd like to automate video uploads for note.
What I made
It's a Python script that converts MP4 videos to GIFs. I implemented the following features:
Frame rate adjustment: Can specify GIF fps (default is 10fps)
Size adjustment: Resize by specifying width (maintains aspect ratio)
Time range specification: Convert partially by specifying start position and duration
File size display: Displays the converted file size in MB
Code
#!/usr/bin/env python3
"""
MP4動画をGIFに変換するスクリプト
使い方:
python mp4_to_gif.py input.mp4 output.gif
オプション:
--fps: GIFのフレームレート (デフォルト: 10)
--width: GIFの幅 (デフォルト: 元のサイズ)
--start: 開始時間(秒) (デフォルト: 0)
--duration: 長さ(秒) (デフォルト: 全体)
"""
import sys
import argparse
from pathlib import Path
try:
from moviepy.editor import VideoFileClip
except ImportError:
try:
from moviepy import VideoFileClip
except ImportError:
print("Error: moviepy がインストールされていません")
print("以下のコマンドでインストールしてください:")
print(" pip install moviepy")
sys.exit(1)
def convert_mp4_to_gif(
input_file: str,
output_file: str,
fps: int = 10,
width: int = None,
start_time: float = 0,
duration: float = None
):
"""
MP4動画をGIFに変換する
Args:
input_file: 入力MP4ファイルのパス
output_file: 出力GIFファイルのパス
fps: GIFのフレームレート
width: GIFの幅(Noneの場合は元のサイズ)
start_time: 開始時間(秒)
duration: 長さ(秒、Noneの場合は全体)
"""
print(f"変換開始: {input_file} -> {output_file}")
# 動画を読み込む
clip = VideoFileClip(input_file)
# 時間範囲を指定
if start_time > 0 or duration is not None:
end_time = start_time + duration if duration else clip.duration
clip = clip.subclip(start_time, end_time)
# サイズを調整
if width:
# 幅を指定して、アスペクト比を維持してリサイズ
height = int(clip.h * width / clip.w)
# moviepyのバージョンによってメソッド名が異なる
if hasattr(clip, 'resize'):
clip = clip.resize((width, height))
else:
clip = clip.resized((width, height))
print(f"元の動画: {clip.duration:.2f}秒, {clip.w}x{clip.h}")
print(f"GIF設定: fps={fps}, width={clip.w}")
# GIFに変換
clip.write_gif(output_file, fps=fps)
clip.close()
# ファイルサイズを表示
output_path = Path(output_file)
file_size = output_path.stat().st_size / (1024 * 1024) # MB
print(f"変換完了: {output_file} ({file_size:.2f} MB)")
def main():
parser = argparse.ArgumentParser(
description="MP4動画をGIFに変換",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
例:
# 基本的な変換
python mp4_to_gif.py video.mp4 output.gif
# フレームレートと幅を指定
python mp4_to_gif.py video.mp4 output.gif --fps 15 --width 800
# 10秒目から5秒間を変換
python mp4_to_gif.py video.mp4 output.gif --start 10 --duration 5
"""
)
parser.add_argument("input", help="入力MP4ファイル")
parser.add_argument("output", help="出力GIFファイル")
parser.add_argument("--fps", type=int, default=10, help="フレームレート (デフォルト: 10)")
parser.add_argument("--width", type=int, help="GIFの幅(省略時は元のサイズ)")
parser.add_argument("--start", type=float, default=0, help="開始時間(秒)")
parser.add_argument("--duration", type=float, help="長さ(秒)")
args = parser.parse_args()
# 入力ファイルの存在確認
if not Path(args.input).exists():
print(f"Error: 入力ファイルが見つかりません: {args.input}")
sys.exit(1)
try:
convert_mp4_to_gif(
args.input,
args.output,
fps=args.fps,
width=args.width,
start_time=args.start,
duration=args.duration
)
except Exception as e:
print(f"Error: 変換中にエラーが発生しました: {e}")
sys.exit(1)
if __name__ == "__main__":
main()How to use
1. Install the necessary libraries
pip install moviepy2. Basic conversion
python mp4_to_gif.py video.mp4 output.gifYou can convert with just this. By default, it converts at 10fps and the original size.
3. Conversion with options specified
Resize width to 800px and convert at 15fps
python mp4_to_gif.py video.mp4 output.gif --fps 15 --width 800Convert only 5 seconds starting from the 10-second mark
python mp4_to_gif.py video.mp4 output.gif --start 10 --duration 5Example of combining options
python mp4_to_gif.py video.mp4 output.gif --fps 12 --width 600 --start 5 --duration 10Tried using it in practice
I tried converting a screen recording of the micro:bit (approx. 7 seconds, 7MB) into a GIF.
Pattern 1: Default settings
python mp4_to_gif.py demo_accel.mov output_accel.gif→ Output: 5.5MB (original size, fps=10)
By the way... at this size, upload failures happen frequently (it failed to upload).
Pattern 2: Resized to 800px width
python mp4_to_gif.py demo_accel.mov output_accel_800.gif --width 800
→ Output: 2.1MB (800px width, fps=10)
By reducing the width, I was able to cut the file size by about 60%. For posting on note, a width of around 800px is just the right size.
Adjusting file size
You can adjust the GIF file size using the following:
Lower the fps (frame rate): Around 10fps is smooth enough to look good
Reduce the width: Around 800px is still easy enough to see
Shorten the length: Cut out only the necessary parts
If the file size is too large, please adjust it using the methods above.
Bonus: Google Colab program
I have made it so it runs on Google Colab below. Please feel free to use it.
Summary
I created a simple tool for embedding videos in note.
I think it's useful for operation demos that don't require audio, or when you want to show a little bit of movement.
Thank you for reading until the end!
I usually write articles about electronics and crafting as "Hacking Papa," so please take a look at those as well.
Click here for Hacking Papa ↓
いいなと思ったら応援しよう!
いつも読んで頂きありがとうございます!
いただいたサポートは子どものためのもの作りの活動費に使わせていただきます!
