Skip to content

Instantly share code, notes, and snippets.

@jaymcgavren
Created September 8, 2026 05:56
Show Gist options
  • Select an option

  • Save jaymcgavren/3b3c2512d068c3a7f00fc02b6ef9616f to your computer and use it in GitHub Desktop.

Select an option

Save jaymcgavren/3b3c2512d068c3a7f00fc02b6ef9616f to your computer and use it in GitHub Desktop.
A Ruby script that uses ffmpeg to overlay images on a video
#!/usr/bin/env ruby
# Lays one or more images over a video. Each image has its own timing, opacity,
# size and position.
#
# Every --image starts a new overlay. Options before the first --image set the
# defaults for all overlays; options after one apply to that overlay only.
#
# video_images.rb --duration 5 \
# -i logo.png -s 0 -x 1 -y 0 --width 200 \
# -i arrow.png -s 3 -d 2 -o 0.5 -x 0.5 -y 0.75 \
# gameplay.mp4
#
# Positions are fractions of the frame, so they hold at any aspect ratio: 0 is
# the left or top edge, 1 the right or bottom edge, 0.5 the middle.
#
# The video is re-encoded at near-lossless quality; the audio is copied untouched.
require "optparse"
ENCODE = %w[-c:v libx264 -crf 16 -preset slow -pix_fmt yuv420p -c:a copy]
DEFAULTS = { start: 0.0, duration: 3.0, opacity: 1.0,
x: 0.5, y: 0.5, align: nil, width: nil, height: nil }
# The point of the image that sits at the x/y position.
ANCHORS = { "left" => 0.0, "center" => 0.5, "right" => 1.0,
"top" => 0.0, "middle" => 0.5, "bottom" => 1.0 }
# Reads the options into a list of overlays, and leaves the file names in argv.
def parse_overlays(argv)
defaults = DEFAULTS.dup
overlays = []
# Send a setting to the overlay being built, or to the defaults if there is none yet.
assign = lambda { |key, value| (overlays.last || defaults)[key] = value }
parser = OptionParser.new do |opt|
opt.banner = "Usage: video_images.rb [options] INPUT [OUTPUT]"
opt.on("-i", "--image FILE", "start an overlay with this picture") { |v| overlays << defaults.merge(image: v) }
opt.on("-s", "--start SECS", Float, "when it appears (default: #{defaults[:start]})") { |v| assign.call(:start, v) }
opt.on("-d", "--duration SECS", Float, "how long it stays (default: #{defaults[:duration]})") { |v| assign.call(:duration, v) }
opt.on("-o", "--opacity NUM", Float, "0 to 1 (default: #{defaults[:opacity]})") { |v| assign.call(:opacity, v) }
opt.on("-x", "--x FRACTION", Float, "0 at the left edge, 1 at the right (default: #{defaults[:x]})") { |v| assign.call(:x, v) }
opt.on("-y", "--y FRACTION", Float, "0 at the top edge, 1 at the bottom (default: #{defaults[:y]})") { |v| assign.call(:y, v) }
opt.on("-a", "--align WORDS", "which part of the image sits at x/y: #{ANCHORS.keys.join(', ')}, or a pair like top-left (default: the part nearest the position)") do |v|
unknown = v.split("-") - ANCHORS.keys
abort "unknown alignment: #{unknown.join(', ')}" unless unknown.empty?
assign.call(:align, v)
end
opt.on("--width PIXELS", Integer, "scale the image to this width (default: its own)") { |v| assign.call(:width, v) }
opt.on("--height PIXELS", Integer, "scale the image to this height (default: its own)") { |v| assign.call(:height, v) }
opt.on("-h", "--help") { puts opt; exit }
end
parser.parse!(argv)
abort parser.help if argv.empty?
abort "give at least one --image" if overlays.empty?
overlays
end
# Names the output after the input: clip.mp4 becomes clip.images.mp4.
def default_output(input)
extension = File.extname(input)
input.delete_suffix(extension) + ".images" + extension
end
# Resizes the image. A width or a height on its own keeps the original shape;
# with neither, iw and ih leave the image as it is.
def scale(overlay)
width = overlay[:width] || (overlay[:height] ? -1 : "iw")
height = overlay[:height] || (overlay[:width] ? -1 : "ih")
"scale=#{width}:#{height}"
end
# Where in the frame one edge of the image goes. W and H are the size of the
# video frame, w and h the size of the scaled image. Without an --align word the
# anchor follows the position, so x=0 puts the left edge at the left of the frame
# and x=1 the right edge at the right, and the image is never cut off.
def place(overlay)
anchor = lambda do |words, position|
word = overlay[:align].to_s.split("-").find { |w| words.include?(w) }
word ? ANCHORS[word] : position
end
"x=W*#{overlay[:x]}-w*#{anchor.call(%w[left center right], overlay[:x])}" \
":y=H*#{overlay[:y]}-h*#{anchor.call(%w[top middle bottom], overlay[:y])}"
end
# Builds the filter graph. Each image is scaled and faded to its own opacity,
# then laid over the result of the overlay before it, so they stack in the order
# given. Returns the graph and the name of the finished video.
def filter_graph(overlays)
video = "0:v"
steps = overlays.each_with_index.map do |overlay, index|
image = "image#{index}"
result = "step#{index}"
step = "[#{index + 1}:v]#{scale(overlay)},format=rgba,colorchannelmixer=aa=#{overlay[:opacity]}[#{image}];" \
"[#{video}][#{image}]overlay=#{place(overlay)}" \
":enable='between(t,#{overlay[:start]},#{overlay[:start] + overlay[:duration]})'[#{result}]"
video = result
step
end
[steps.join(";"), "[#{video}]"]
end
overlays = parse_overlays(ARGV)
input = ARGV.shift
output = ARGV.shift || default_output(input)
([input] + overlays.map { |overlay| overlay[:image] }).each do |file|
abort "#{file}: no such file" unless File.exist?(file)
end
abort "#{output} already exists; delete it or name another output file" if File.exist?(output)
inputs = ["-i", input] + overlays.flat_map { |overlay| ["-i", overlay[:image]] }
graph, video = filter_graph(overlays)
puts "#{overlays.length} image overlays -> #{output}"
# Keep the sound of the video, if it has any.
exit 1 unless system("ffmpeg", *inputs, "-filter_complex", graph,
"-map", video, "-map", "0:a?", *ENCODE, output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment