Create a video thumbnail automatically— Ruby on Rails

Ivan
2 min readJul 16, 2020

--

I’ve just spent some 3h trying to figure out a way to automatically create a thumbnail for an uploaded video, and I thought to write a quick tutorial to help all of you with the same problem. The solution is quite simple, but I haven’t been able to find a simple answer anywhere.

My problem: I have a Rails app with Active Storage and Video post. I have a page where I show 3 videos and I don’t want to load all 3 videos when someone visits the page. My goal was to create 3 thumbnails for each video and show them on the page. I will use JS to handle the click on the thumbnail and play the video in a popup.

The first step is to add an attachment to the Video model:

class Video < ApplicationRecord
has_one_attached :clip
end

The second step is to install FFmpeg locally. If you’re using Ubuntu here is how:

$ sudo apt update
$ sudo apt install ffmpeg

If you’re using Docker, just add the command to the Dockerfile:

RUN apt-get update -y && apt-get install ffmpeg

The third step is to output the thumbnail of your video in view:

<%= image_tag url_for(video.clip.preview(resize_to_limit: [300, 300]).processed) %>

Set the dimensions of the thumbnail and that’s it!

In addition: if you’re using Heroku, here is the command that you should run from the Heroku CLI to install FFmpeg:

$ heroku buildpacks:add -i 1 https://github.com/heroku/heroku-buildpack-activestorage-preview

Hope this helps!

--

--