Wednesday 23 November 2011

Rails: ffmpeg video generation from images

To generate video from a series of images/photos in rails, I use this code snippet:

    # generate the video and store it under the appropriate public path.
    def create_video_from(foto_paths = [], tyype)
      create_tmp_links(foto_paths)
      status = Paperclip.run('ffmpeg', ffmpeg_options)
      remove_tmp_links(foto_paths.length)
      FileUtils.mv('/tmp/output.mp4', Rails.root.to_s + "/public/#{tyype.to_s}_video.mp4")
    end

    def ffmpeg_options
      "-r 1 -f image2 -i '/tmp/img%03d.jpg' /tmp/output.mp4"
    end

    # ffmpeg requires filenames matching a pattern, so create them under /tmp
    def create_tmp_links(foto_paths = [])
      foto_paths.each_with_index do |path, i|
        tmp_path = "/tmp/img%03d.jpg" % (i + 1)
        File.symlink(path, tmp_path)
      end
      true
    end

    # remove those symlinks
    def remove_tmp_links(fotos_cnt = 0)
      fotos_cnt.times do |i|
        tmp_path = "/tmp/img%03d.jpg" % (i + 1)
        File.unlink(tmp_path)
      end
      true
    end

Hope it helps!

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Hey great post, Can you share your rails code ? i am trying to make a presentation from images on rails . thank you

    ReplyDelete
    Replies
    1. Thanks Vivek.

      This is more of an abstract code and makes more sense when its not bundled within my application. You should be able to just include these methods in your model(integrated with paperclip) and it should work seamlessly.

      Let me know if there are any issues.

      Delete