ruby - 如何使用 CarrierWave 更正文件缩略图生成的文件扩展名

标签 ruby file-upload ruby-on-rails-3.1 carrierwave

我要上传文件并为其转换缩略图。

我的代码是:

require 'streamio-ffmpeg'
module CarrierWave
  module FFMPEG
    module ClassMethods
      def resample(bitrate)
        process :resample => bitrate
      end

      def gen_video_thumb(width, height)
        process :gen_video_thumb => [width, height]
      end
    end

    #def is_video?
    #  ::FFMPEG::Movie.new(File.open(store_path)).frame_rate != nil
    #end

    def gen_video_thumb(width, height)
      directory = File.dirname(current_path)
      tmpfile = File.join(directory, "tmpfile")

      FileUtils.move(current_path, tmpfile)
      file = ::FFMPEG::Movie.new(tmpfile)
      file.transcode(current_path, "-ss 00:00:01 -an -r 1 -vframes 1 -s #{width}x#{height}")

      FileUtils.rm(tmpfile)
    end

    def resample(bitrate)
      directory = File.dirname(current_path)
      tmpfile = File.join(directory, "tmpfile")

      File.move(current_path, tmpfile)

      file = ::FFMPEG::Movie.new(tmpfile)
      file.transcode(current_path, :audio_bitrate => bitrate)

      File.delete(tmpfile)
    end
  end
end

我的上传者有

  version :thumb do
    process :resize_to_fill => [100, 70], :if=> :image?
    process :gen_video_thumb => [100, 70], :if=> :video? do
      process :convert => 'png'
    end
  end

函数是。

  protected

  def image?(new_file)
    ::FFMPEG::Movie.new(new_file.file.path).frame_rate == nil
  end

  def video?(new_file)
    ::FFMPEG::Movie.new(new_file.file.path).frame_rate != nil
  end

但问题是,视频上传了,视频thubmail生成的很好。但它没有 png 扩展名。如果我上传一个 mp4 文件,它的缩略图也有一个 mp4 扩展名。但那是可以在浏览器中查看的图像。

如何更正扩展问题?谁能指出代码中的问题?

最佳答案

我最近通过覆盖 :thumb 版本的 full_filename 方法解决了这个问题

version :thumb do
  # do your processing
  process :whatever

  # redefine the name for this version
  def full_filename(for_file=file)
    super.chomp('mp4') + 'png'
  end
end

我调用 super 获取默认的 :thumb 文件名,然后将扩展名从 mp4 更改为 png ,但你可以做任何事情。

更多信息,carrierwave wikiHow to: Customize your version file names 上有一篇好文章.查看其他 wiki 页面以获得很多想法。

关于ruby - 如何使用 CarrierWave 更正文件缩略图生成的文件扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9134240/

相关文章:

Ruby 和 Redis,线程不处理命令

ruby - 混淆 base64 类方法的使用

ruby-on-rails - 我想了解 Paperclip gem 如何处理 s3 停机时间

html - CKEditor Blazor 集成

ruby-on-rails - 渲染部分布局不显示任何内容

ruby - 在 Ruby 中测试标准输入

php - 为什么带有图像扩展名的文件作为 php 文件执行?

java - 从 Java 库更改提示错误消息

ruby-on-rails-3.1 - 在 rails 测试输出中缺少进度点和 0% 通过(测试单元,Rails 3.1 rc6,Ruby 1.9.2)

ruby - 轨道 3.1 : Upgrading caused my link_to path routes to break?