在 Ruby Paperclip GEM 中获取模型中图像的宽度和高度 [英] Getting width and height of image in model in the Ruby Paperclip GEM
本文介绍了在 Ruby Paperclip GEM 中获取模型中图像的宽度和高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试在初始保存时仍在模型中时获取上传图像的宽度和高度.
Trying to get the width and height of the uploaded image while still in the model on the initial save.
有没有办法做到这一点?
Any way to do this?
这是我一直在用我的模型测试的代码片段.当然,它在instance.photo_width"上失败了.
Here's the snippet of code I've been testing with from my model. Of course it fails on "instance.photo_width".
has_attached_file :photo,
:styles => {
:original => "634x471>",
:thumb => Proc.new { |instance|
ratio = instance.photo_width/instance.photo_height
min_width = 142
min_height = 119
if ratio > 1
final_height = min_height
final_width = final_height * ratio
else
final_width = min_width
final_height = final_width * ratio
end
"#{final_width}x#{final_height}"
}
},
:storage => :s3,
:s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
:path => ":attachment/:id/:style.:extension",
:bucket => 'foo_bucket'
所以我基本上是在尝试这样做,以根据初始图像尺寸获得自定义缩略图宽度和高度.
So I'm basically trying to do this to get a custom thumbnail width and height based on the initial image dimensions.
有什么想法吗?
推荐答案
啊,想通了.我只需要制作一个过程.
Ahh, figured it out. I just needed to make a proc.
这是我的模型中的代码:
Here's the code from my model:
class Submission < ActiveRecord::Base
#### Start Paperclip ####
has_attached_file :photo,
:styles => {
:original => "634x471>",
:thumb => Proc.new { |instance| instance.resize }
},
:storage => :s3,
:s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
:path => ":attachment/:id/:style.:extension",
:bucket => 'foo_bucket'
#### End Paperclip ####
def resize
geo = Paperclip::Geometry.from_file(photo.to_file(:original))
ratio = geo.width/geo.height
min_width = 142
min_height = 119
if ratio > 1
# Horizontal Image
final_height = min_height
final_width = final_height * ratio
"#{final_width.round}x#{final_height.round}!"
else
# Vertical Image
final_width = min_width
final_height = final_width * ratio
"#{final_height.round}x#{final_width.round}!"
end
end
end
这篇关于在 Ruby Paperclip GEM 中获取模型中图像的宽度和高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文