我的要求是在上传pdf文件时将pdf转换为图像。到目前为止这就是我所做的。
class ImageUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
include CarrierWave::MiniMagick
include CarrierWave::MimeTypes
# Choose what kind of storage to use for this uploader:
storage :file
# storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"#{PRIVATE_UPLOADS_PATH}/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
# def default_url
# # For Rails 3.1+ asset pipeline compatibility:
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
#
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
# end
process :set_content_type
process :set_model_ext_attributes
# Create different versions of your uploaded files:
version :large, if: :image? do
process :resize_and_pad => [800, 600]
end
version :thumb, if: :image? do
process :resize_and_pad => [100, 100]
end
version :normal, if: :pdf? do
process :efficient_conversion => [640, 960]
end
def efficient_conversion(width, height)
manipulate! do |img|
img.format("png") do |c|
c.fuzz "3%"
c.trim
c.resize "#{width}x#{height}>"
c.resize "#{width}x#{height}<"
end
img
end
end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
def extension_white_list
%w(jpg jpeg gif png pdf)
end
def set_model_ext_attributes
model.display_filename ||= file.filename
model.content_type_cd = CONTENT_TYPES.rassoc(file.content_type).first if file.content_type
model.file_size = file.size
end
def content_type
CONTENT_TYPES.assoc(model.content_type_cd).last
end
# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
# def filename
# "something.jpg" if original_filename
# 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
end
但是我一直在说错误
MiniMagick::Error: Unable to format to png
from /Users/rkamat/.rvm/gems/ruby-1.9.3-p547/gems/mini_magick-3.7.0/lib/mini_magick/image.rb:266:in `format'
在这下面的行
img.format("png") do |c|
任何有关这方面的帮助都会受到赞赏,因为我花了几个小时试图推迟这个。
我已经参考了carrierwave上传中的文档,以使其正常运行https://github.com/carrierwaveuploader/carrierwave/wiki/Efficiently-converting-image-formats
答案 0 :(得分:1)
如果你使用RMagick
require 'RMagick'
pdf_file = Magick::ImageList.new('your_file.pdf')
PDF是图像列表(more info with ImageMagick)。