我有类似的东西:
class User < ApplicationRecord
has_one_attached :avatar do |attachable|
attachable.variant :large, resize_to_limit: [300, nil]
attachable.variant :medium, resize_to_limit: [100, nil]
attachable.variant :small, resize_to_limit: [ 50, nil]
end
end
我如何创建...
[x, y, width, height]
是否可以以某种方式“将坐标传递给模型”?如果是的话,怎么办?
如果不是:裁剪是否需要在控制器操作中单独进行,创建(原始文件的)裁剪版本,并基于该版本创建“命名变体”?如果是这样,那看起来怎么样?
这已添加到 Rails 7 中 (https://github.com/rails/rails/pull/39135):
class User < ActiveRecord::Base
has_one_attached :avatar, variants: {
thumb: { resize: "100x100" },
medium: { resize: "300x300", monochrome: true }
}
end
class Gallery < ActiveRecord::Base
has_many_attached :photos, variants: {
thumb: { resize: "100x100" },
medium: { resize: "300x300", monochrome: true }
}
end
<%= image_tag user.avatar.variant(:thumb) %>
我会尽力回答你的问题:
user.avatar.variant(:large)
。如果在视图中完成,请附加 .processed
以检索已生成的变体(如果存在)。resize_to_limit: [300, 100], crop: '200x300+0+0'
如果你想从参数中获取尺寸和坐标,那么我不会使用命名变体,而是使用类似的东西
在模型中:
has_one_attached :avatar
在控制器中:
def image_height
params[:height]
end
def generate_variant_small
@user.avatar.variant(resize_to_limit: "300x#{image_height}^", crop: '200x300+0+0').processed
end
使用新语法:
图像魔法
has_one_attached :image do |blob|
blob.variant :small, resize: "720x400"
end
贵宾
has_one_attached :image do |blob|
blob.variant :small, resize_to_limit: [720, 400]
end