我的FileHandler模型可以允许所有类型的文件
class FileHandler < ActiveRecord::Base
serialize :properties, ActiveRecord::Coders::Hstore
mount_uploader :file_path, FileUploader
//I'm already setting some of the file attributes here
def update_file_attributes
if file_path.present? && file_path_changed?
self.file_name = file_path.file.filename
self.file_type = file_path.file.content_type
self.file_size = file_path.file.size
end
end
//I want to get height and width here
#Hstore
%w[ImageHeight ImageWidth].each do |key|
attr_accessible key
define_method(key) do
properties && properties[key]
end
define_method("#{key}=") do |value|
self.properties = (properties || {}).merge(key => value)
end
end
我的fileUploader类
class FileUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
include CarrierWave::RMagick
version :big, :if => :image? do
process :resize_to_limit => [760, nil]
end
version :thumb_big, :if => :image? do
process :resize_to_limit => [200, 200]
end
version :thumb, :if => :image? do
process :resize_to_limit => [160, 160]
end
version :tiny, :if => :image? do
process :resize_to_limit => [40, 40]
end
protected
def image?(new_file)
new_file.content_type.include? 'image'
end
end
我的问题是,如何获取原始图像的高度和宽度属性并将其存储在hstore字段中? 任何帮助将不胜感激。
答案 0 :(得分:3)
试试这个
class FileUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
include CarrierWave::RMagick
process :store_geometry, :if => :image?
#......
#......
#......
def store_geometry
if image?(@file)
img = ::Magick::Image::read(@file.file).first
if model
model.ImageWidth = img.columns
model.ImageHeight = img.rows
end
end
end
end
#Hstore
%w[ImageHeight ImageWidth].each do |key|
attr_accessible key
define_method(key) do
properties && properties[key]
end
define_method("#{key}=") do |value|
self.properties = (properties || {}).merge(key => value)
end
end
假设
我假设您有使用图像方法检查文件是否为图像的原因,这也意味着您还要上传其他文件格式。好吧,我在这里很好地使用它,它只在文件是图像时才调用process_geometry方法。
希望它有所帮助。
答案 1 :(得分:1)
根据我所知,你可以使用Rmagick
来获取Image的维度
我记得你能做的就是这个
img = Magick::Image::read("image_file").first
img.columns => width of image
img.rows => height of image
也许那时你可以在HSTORE中设置它们
希望这个帮助
由于
答案 2 :(得分:1)
作为汤米评论的补充。这就是我所做的,以保存每个特定图像版本的大小,而不仅仅是原始图像的大小。你必须在你的模型中添加“几何”字段,这样你就会有类似的东西:“phone = 146x220&amp; tablet = 292x440”
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
storage :file
version :thumb do
process :resize_to_fill => [80, 80]
end
version :phone do
process :resize_to_limit => [290, 220]
process :store_geometry => :phone
process :quality => 75
end
version :tablet do
process :resize_to_limit => [580, 440]
process :store_geometry => :tablet
process :quality => 35
end
process
def extension_white_list
%w(jpg jpeg gif png)
end
def store_geometry(version)
manipulate! do |img|
model.geometry ||= ""
model.geometry << "&" unless model.geometry.empty?
model.geometry << "#{version}=#{img.columns}x#{img.rows}"
img
end
end
end