2013-04-24 13 views
3

我可以上傳PDF並將其轉換爲PNG格式,並通過<%= image_tag "path/to/image" %>助手在瀏覽器中正確呈現。但是,實際的文件擴展名不會從PDF更改爲PNG。所以如果你下載圖像,它會以image.pdf的形式下載。下載完成後,如果手動將擴展名更改爲'png',它會在本地機器上正確打開圖像軟件。我希望RMagick進程自動更改擴展名以及文件格式。我可以編寫一些代碼去除PDF,並在文件保存時添加PNG擴展名,但似乎我在這裏丟失了一些東西。我想這是當我轉換成不同格式時應該自動完成的事情。這是我的ImageUploader.rb類。我正在使用Carrierwave和RMagick。Rails 4 Carrierwave + RMagick,將PDF轉換爲PNG會更改文件編碼,但不能擴展?

# app/uploads/image_uploader.rb 
class ImageUploader < CarrierWave::Uploader::Base 
    include CarrierWave::RMagick 
    include Sprockets::Rails::Helper 

    storage :file 

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

    process :convert_to_png 

    def convert_to_png 
    manipulate!(format: "png", read: { density: 400 }) do |img, index, options| 
     options = { quality: 100 } 
     img.resize_to_fill!(850, 1100) 
     img 
    end 
    end 

# Add 'png' file extension so file becomes 'image.pdf.png' 
def filename 
    "#{original_filename}.png" if original_filename 
    end 
end 

回答

1

這是怎麼了處理它:

version :pdf_thumb, :if => :pdf? do 
    process :thumbnail_pdf 
    process :set_content_type_png 

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

def thumbnail_pdf 
    manipulate! do |img| 
    img.format("png", 1) 
    img.resize("150x150") 
    img = yield(img) if block_given? 
    img 
    end 
end 

def set_content_type_png(*args) 
    self.file.instance_variable_set(:@content_type, "image/png") 
end 
0

我還試圖爲上傳的PDF創建縮略圖,到目前爲止,它對單頁pdf很好。對於多頁面pdf,該方法根據需要創建縮略圖,但在打開文件時,會顯示「致命錯誤,讀取PNG圖像文件:不是PNG文件」。

這是我正在做它:

version :pdf_thumb, :if => :pdf? do 
    process :convert => 'png' 
    process :resize_to_limit => [120, 120] 
    def full_filename (for_file = model.artifact.file) 
     super.chomp(File.extname(super)) + '.png' 
    end 
    end 
protected 

    def pdf?(new_file) 
    new_file.content_type.include? "/pdf" 
    end 

所以,我想知道你是如何能夠執行從PDF創建縮略圖?