LoginSignup
1

More than 5 years have passed since last update.

rails controllerから、ffmpeg使って動画のサムネイルをbase64で取得

Posted at

やりたかったこと

動画の初めの画像をthumbnailとして作成したかった。

thumbnail画像のuploaderは、carrierwave-base64を使って作成している。

画像・動画共に作成したthumbnailの保存はcarrierwave-base64にまとめてしまいたかったので、carrierwave-base64にbase64エンコードされた画像を渡したい。

メディアファイルは、api経由で、movie, imageに格納されて送られてくる。

以下のやり方でbase64エンコードした画像を受け取って、あげればよい。

thumbnail_controller.rb


def get_base64_video_thumbnail
    i_path = @poster.movie.path
    o_path = "./public/uploads/tmp/#{SecureRandom.hex(10)}.jpeg"
    begin
      system "ffmpeg -itsoffset -1 -i #{i_path} -s 300x300 -y -vframes 1 -f image2 -an #{o_path}"
      ret_base64_img = "data:image/jpeg;base64," + Base64.encode64(File.new(o_path).read)
      File.delete(o_path)
      return ret_base64_img
    rescue => e
      render json: {
        message: I18n.t("controllers.posters.fail_create_thumbnail")
      }, :status => :unprocessable_entity and return
    end
end

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1