CarrierWave RMagick为图像和PDF创建缩略图

时间:2015-05-26 09:55:31

标签: ruby-on-rails carrierwave rmagick

用户可以上传图片或PDF。我想显示一个小缩略图(PDF的第一页)

此代码适用于图像,但不适用于PDF。

  version :thumb, :if => :image? do
    process :resize_to_limit => [80, 80]
  end

  version :thumb, :if => :pdf? do
    process :cover
    process :resize_to_fill => [80, 80]
    process :convert => :jpg

    def full_filename (for_file = model.source.file)
      super.chomp(File.extname(super)) + '.jpg'
    end
  end


  def cover 
    manipulate! do |frame, index|
      frame if index.zero?
    end
  end

  protected

    def image?(new_file)
      new_file.content_type.start_with? 'image'
    end

    def pdf?(new_file)
      new_file.content_type.end_with? 'pdf'
    end

1 个答案:

答案 0 :(得分:0)

对于 pdf 最好的方法是:

require 'rmagick'

pdf_path = "/file.pdf"
first_page = "#{pdf_path}[0]" # first page in PDF
pdf = Magick::ImageList.new(first_page) # faster than load all pages and select first
thumb = pdf.scale(70, 100)
thumb.write("#{new_path}/thumb.jpg")