我在使用 Carrierwave-Video 上传肖像视频时遇到问题 gem 。上传纵向视频(特别是在移动设备上拍摄的视频)时,它们会顺时针旋转 90 度。在 Carrierwave-Video 文档中,有一个动态配置选项,但我没有看到一种动态传递自定义参数以根据视频方向对视频进行转码的方法。我知道如果我运行以下行,我可以将视频逆时针旋转 90 度:
encode_video(:mp4, custom: "-vf transpose=1")
但是我需要一种可靠的方法来检测视频是否需要旋转。我想知道是否有某种方法可以使用 ffmpeg 运行条件参数,该参数仅在视频为纵向时运行。
如果它有帮助的话,这就是我的 Rails 应用程序中的视频 uploader 的样子(由于某种原因,转码过程甚至在检测到视频方向之前就已经运行):
require 'carrierwave/processing/mime_types'
class VideoPathUploader < CarrierWave::Uploader::Base
include CarrierWave::Video
include CarrierWave::Video::Thumbnailer
include CarrierWave::MimeTypes
process :encode
def encode
Rails.logger.debug "in encode"
video = FFMPEG::Movie.new(@file.path)
video_width = video.width
video_height = video.height
Rails.logger.debug "video widthxheight: #{video.width}x#{video.height}"
aspect_ratio = video_width/video_height
if video_height > video_width
# rotate video
Rails.logger.debug "portrait video"
encode_video(:mp4, custom: "-vf transpose=1", aspect: aspect_ratio)
else
encode_video(:mp4, aspect: aspect_ratio)
end
instance_variable_set(:@content_type, "video/mp4")
:set_content_type_mp4
end
end
最佳答案
我能够通过使用 mini_exiftool 解决该问题 gem 。在我的计算机上安装 exiftool 后(使用brew install exiftool),我能够获取上传视频的方向和宽高比,并使用它来确定是否使用 ffmpeg 对视频应用转换。这是我的最终上传者:
require 'carrierwave/processing/mime_types'
require 'rubygems'
require 'mini_exiftool'
class VideoPathUploader < CarrierWave::Uploader::Base
process :encode
def encode
video = MiniExiftool.new(@file.path)
orientation = video.rotation
if orientation == 90
# rotate video
Rails.logger.debug "portrait video"
aspect_ratio = video.imageheight.to_f / video.imagewidth.to_f
encode_video(:mp4, custom: "-vf transpose=1", aspect: aspect_ratio)
else
aspect_ratio = video.imagewidth.to_f / video.imageheight.to_f
encode_video(:mp4, resolution: :same, aspect: aspect_ratio)
end
instance_variable_set(:@content_type, "video/mp4")
:set_content_type_mp4
end
end
此外,如果它有帮助,我还必须在 Heroku 上安装 exiftool 才能将其与我的 Rails 应用程序一起使用。我通过使用以下构建包做到了这一点:
https://github.com/benalavi/buildpack-exiftool
安装 buildpack 后,我仍然必须手动指定 exiftool 的路径(它应该在安装 buildpack 时自动执行此操作,但它没有为我执行此操作)。我通过手动设置路径来做到这一点:
heroku config:set PATH=*all_your_other_paths*:vendor/exiftool-9.40/bin
关于ruby-on-rails - ffmpeg视频的条件旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21709900/