2017-08-14 71 views
0

我將上傳的PDF轉換爲圖像,每頁一個圖像。我已經想出瞭如何使用MiniMagick::Tool::Convert生成圖像,但我不知道如何編寫上傳器的version塊,以便我可以訪問一組圖像URL。如何使用Carrierwave和MiniMagick(Ruby on Rails)將PDF轉換爲圖像數組

這裏是我上傳至今:

class DocumentUploader < CarrierWave::Uploader::Base 
    include CarrierWave::MiniMagick 

    storage :file 
    # storage :fog 

    def store_dir 
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" 
    end 

    version :jpg do 
    process :convert_to_images 
    process :set_content_type_jpg 

    def convert_to_images(*args) 
     image = MiniMagick::Image.open(current_path) 
     image.pages.each_with_index do |page, index| 
     MiniMagick::Tool::Convert.new do |convert| 
      convert.background 'white' 
      convert.flatten 
      convert.density 300 
      convert.quality 95 
      convert << page.path 
      convert << "#{CarrierWave.root}/#{store_dir}/image-#{index}.jpg" 
     end 
     end 
    end 
    end 

    def set_content_type_jpg(*args) 
    self.file.instance_variable_set(:@content_type, "image/jpg") 
    end 

    # Add a white list of extensions which are allowed to be uploaded. 
    def extension_white_list 
    %w(jpg jpeg gif png doc docx pdf) 
    end 
end 

這在正確的目錄下生成image-0.jpgimage-1.jpg等。但是現在我無法在我的觀點中引用這些圖像,甚至不知道有多少圖像。當我需要將圖像上傳到S3時,這也不起作用。我如何才能讓Carrierwave處理這個圖像集合的文件存儲,而不是單個圖像?

它也看起來像我可能需要添加一個新的數據庫列來存儲頁數。有沒有辦法讓我的上傳者根據這個計數返回一組圖片網址?

我也願意切換到另一個寶石。用回形針,神龕或Refile,這會更容易些嗎?

回答

1

隨着靖國神社就可以使每個頁面不同的版本:

class ImageUploader < Shrine 
    plugin :versions 
    plugin :processing 

    process(:store) do |io, context| 
    pdf  = io.download 
    versions = {} 

    image = MiniMagick::Image.new(pdf.path) 
    image.pages.each_with_index do |page, index| 
     page_image = Tempfile.new("version-#{index}", binmode: true) 
     MiniMagick::Tool::Convert.new do |convert| 
     convert.background 'white' 
     convert.flatten 
     convert.density 300 
     convert.quality 95 
     convert << page.path 
     convert << page_image.path 
     end 
     page_image.open # refresh updated file 
     versions[:"page_#{index + 1}"] = page_image 
    end 

    versions 
    end 
end 

假設你有一個Document模型和你連接一個PDF到file附件欄,然後你可以檢索使用Hash#values頁的數組:

pages = document.file.values 
pages #=> [...array of pages...] 
pages.count #=> number of pages 
相關問題