由于 Paperclip 弃用,我从 Paperclip 切换到 Shrine。
在我的模型Profilepic.rb
文件中,我曾经检索图像变体的尺寸,如下所示:
before_create :save_ratio
def save_ratio
geo = Paperclip::Geometry.from_file(image.queued_for_write[:original])
self.ratio = geo.width / geo.height
end
基本上我正在保存图像的垂直比例。
它与 Paperclip 配合得很好:我在保存值之前抓取了临时图像queued_for_write
并检查了尺寸。Paperclip::Geometry
在 Shrine 中,我向上传者添加了以下内容:
plugin :add_metadata
plugin :store_dimensions
它工作得很好,因为我拥有所有可用信息并且图像已正确上传到 S3。
然而我保存图像比例的新方法不再有效:
after_create :save_ratio
def save_ratio
self.ratio = self.image[:original].width.to_i / self.image[:original].height.to_i
end
我明白了
ProfilepicUploader::UploadedFile:0x00007f69a685c750> 的错误未定义方法“[]”
而在控制台中,创建图像后:
Profilepic.first.image[:original].width.to_i
确实返回正确的值。
编辑
我的上传者:
require "image_processing/mini_magick"
class ProfilepicUploader < Shrine
include ImageProcessing::MiniMagick
plugin :processing
plugin :validation_helpers # to validate image data
plugin :versions
plugin :add_metadata
plugin :store_dimensions
Attacher.validate do
validate_max_size 5.megabyte
validate_mime_type_inclusion ['image/jpg', 'image/jpeg', 'image/png']
end
process(:store) do |io, context|
versions = { original: io } # retain original
io.download do |original|
pipeline = ImageProcessing::MiniMagick.source(original)
versions[:editable] = pipeline.resize_to_fit!(700, 700)
versions[:thumbnail] = pipeline.resize_to_fill!(400, 400)
versions[:small] = pipeline.resize_to_fill!(200, 200)
end
versions # return the hash of processed files
end
end
我的模型:
class Profilepic < ApplicationRecord
require "image_processing/mini_magick"
belongs_to :professionnel
before_create :set_hashid
include ProfilepicUploader::Attachment.new(:image) # adds an `image` virtual attribute
include ProfilepicFinalUploader::Attachment.new(:final_image) # adds an `image` virtual attribute
attr_accessor :crop_x, :crop_y, :crop_w, :crop_h
after_create :save_ratio_image
private
def save_ratio
self.ratio = self.image[:original].width.to_i / self.image[:original].height.to_i
end
end