这是我的上传者:
class PostImageUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
include Sprockets::Helpers::RailsHelper
include Sprockets::Helpers::IsolatedHelper
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
"uploads/posts"
end
version :medium do
process :resize_to_limit => [280, nil]
process :convert => 'jpg'
end
def filename
random_token = Digest::SHA2.hexdigest("#{Time.now.utc}--#{model.id.to_s}").first(20)
ivar = "@#{mounted_as}_secure_token"
token = model.instance_variable_get(ivar)
token ||= model.instance_variable_set(ivar, random_token)
"#{model.title.gsub(" ", "-").downcase}-#{token}.jpg" if original_filename
end
def extension_white_list
%w(jpg jpeg gif png)
end
process :store_dimensions
private
def store_dimensions
if file && model.post_image.medium.present?
model.image_width, model.image_height = ::MiniMagick::Image.open(file.file)[:dimensions]
end
end
end
在本教程中https://github.com/carrierwaveuploader/carrierwave/wiki/How-to%3A-Get-image-dimensions,可以获得原始图片尺寸。但我想获得版本图像尺寸。像这样:
def store_dimensions
if file && model.post_image.medium.present?
model.image_width, model.image_height = ::MiniMagick::Image.open(model.post_image.medium)[:dimensions]
end
end
而不是file.file
,model.post_image.medium
。
问题是此代码在先前创建对象时有效。只有在更新图像时才有效。
我需要在第一次创建时使用此代码。
问候!
答案 0 :(得分:0)
您可以尝试使用callbacks
。 https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-use-callbacks
after :store, :store_dimensions
# rest of uploader codes...
def store_dimensions(file)
model.image_width, model.image_height = ::MiniMagick::Image.open(model.post_image.medium)[:dimensions]
model.save!
end