我使用carrierwave上传图片,我需要获取图片尺寸并在上传时存储它们。
CarrierWave有一个解决方案: https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Get-image-dimensions
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
process :store_dimensions
private
def store_dimensions
if file && model
img = ::Magick::Image::read(file.file).first
model.width = img.columns
model.height = img.rows
end
end
end
虽然我可以看到这将如何将维度存储在名为height&amp;的数据库字段中。单个图像的宽度我正在使用多个文件上传器。 https://github.com/carrierwaveuploader/carrierwave#multiple-file-uploads
如何在上传多个文件时存储这些图片尺寸?
EDIT1
class AttachmentUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
process resize_to_limit: [400, 400]
process :get_geometry
def geometry
@geometry
end
def get_geometry
if (@file)
@geometry = ::MiniMagick::Image.open(@file.file)[:dimensions]
end
end
end
2.4.1 :001 > Post.last.attachments.first.geometry
Post Load (2.8ms) SELECT "posts".* FROM "posts" ORDER BY "posts"."id" DESC LIMIT $1 [["LIMIT", 1]]
=> nil
2.4.1 :002 > Post.last.attachments.first.get_geometry
Post Load (1.9ms) SELECT "posts".* FROM "posts" ORDER BY "posts"."id" DESC LIMIT $1 [["LIMIT", 1]]
=> [400, 200]
EDIT2
如果我使用下面的载波建议将这些val存储在db字段中,那么它适用于单个图像,但是当我上传多个图像时,每个后续图像都会覆盖这些值,因此我可能有三个图像,但只有一个val用于高度和存储宽度。
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
process :store_dimensions
private
def store_dimensions
if file && model
model.width, model.height = ::MiniMagick::Image.open(file.file)[:dimensions]
end
end
end
答案 0 :(得分:1)
根据模特的名称来判断这样的事情吗?
version :post do
process :resize_to_fit => [200, nil]
process :get_geometry
def geometry
@geometry
end
end
def get_geometry
if (@file)
img = ::Magick::Image::read(@file.file).first
@geometry = [ img.columns, img.rows ]
end
end
然后您可以在保存后的回调中读出图像的几何图形并将其保存在模型中的自定义数据库行中。