Rails 7+ Active Storage:如何打开图像变体?

问题描述 投票:0回答:1

最新的 Rails (7.1) 与最新兼容的 ruby (3.2)

我想通过在我的代码中

open
来分析某个图像的变体。但是,我似乎只能访问原始图像。

例如,我有一张大图像(从我的移动设备获取)。我将其上传到我的 Rails 服务器并立即调整大小以适应

attachable.variant :resized, resize_to_limit: [500, 1000], preprocessed: true
。我可以使用
<%= image_tag @bill.receipt.variant(:resized) %>
正确显示调整大小的图像。

image = Bill.last.receipt.blob.open do |r| 
  ImageProcessing::Vips::Processor.load_image(r.path)
end

resized = Bill.last.receipt.variant(:resized).blob.open do |r| 
  ImageProcessing::Vips::Processor.load_image(r.path)
end

puts image # => #<Image 3072x4080 uchar, 3 bands, srgb>
puts [image.width, image.height] # => [3072, 4080]

puts resized # => #<Image 3072x4080 uchar, 3 bands, srgb>
puts [resized.width, resized.height] # => [3072, 4080] but expected is [500, 664]

我尝试上下查找 Rails 指南,进行一些谷歌搜索,但没有任何结果。似乎大多数人关心的是

image_tag
而不是打开调整大小的文件。

有人愿意为我指出正确的方向吗?

ruby-on-rails rails-activestorage
1个回答
0
投票

感谢@schwern 的回答。

我相信

blob
会返回原始的斑点。尝试
image
processed.
– Schwern 17 小时前

resized = Bill.last.receipt.variant(:resized).image.open do |r| 
  ImageProcessing::Vips::Processor.load_image(r.path)
end
# => #<Image 500x664 uchar, 3 bands, srgb>

processed
会出错,因为
open
是对象上的私有方法。

© www.soinside.com 2019 - 2024. All rights reserved.