获取 Active Storage 变体的元数据 [英] Get metadata of Active Storage variant
问题描述
我有一个 Active Storage 映像变体,例如
I have an Active Storage image variant e.g.
<%= image_tag model.logo_image.variant(resize_to_fit: [300, 200]) %>
我正在尝试获取此变体的 width
和 height
值(因为它们未知)以用于 width
和height
HTML 属性.
I'm trying to get the width
and height
values of this variant (since they are unknown) for use in the width
and height
HTML attributes.
我预计他们会在这里:
model.logo_image.variant(resize_to_fit: [300, 200]).processed.blob.metadata
但这给了我原始文件的元数据,而不是调整大小的变体,例如
But this gives me the metadata of the original file not the resized variant e.g.
{"identified"=>true, "width"=>800, "height"=>174, "analyzed"=>true}
如何获取 Active Storage 变体的维度?
How do I get the dimensions of an Active Storage variant?
推荐答案
在 Rails 6.1 中,最后所有的变体都存储在一个新的模型/数据库表中,每个变体都带有一个 Blob.如果此功能与您相关,请尝试升级.
With Rails 6.1, finally all Variations are stored in a new model/database table and each variation with a Blob. Try upgrading, if this feature is relevant for you.
深入到对象中,您可以找到变体 blob,从而找到元数据!
Very deep into the object, you can find then the variation blob, and thus the metadata, though!
试试:
model.logo_image.
variant(resize_to_fit: [300, 200]).
processed.send(:record).image.blob.metadata
尽管第一次不起作用,当第一次调用时,它没有宽度/高度,因为 AnalyzeJob 将异步运行,它会稍后"添加宽度/高度,具体取决于您的队列设置.
It does not work the first time though, when called first time, it has no width/height, because the AnalyzeJob will run asynchronously, and it will add the width/height "later", depending on your queue setup.
也许添加一个 helper_method 来创建具有宽度和高度的图像(如果可用):
Maybe add a helper_method that creates the image with width, height if available:
module ApplicationHelper
def image_tag_for_attachment_with_dimensions(variant, opts = {})
if variant.processed?
metadata = variant.processed.send(:record).image.blob.metadata
if metadata['width']
opts[:width] = metadata['width']
opts[:height] = metadata['height']
end
end
image_tag variant, opts
end
end
# usage:
= image_tag_for_attachment_with_dimensions model.logo_image.variant(resize_to_fit: [300, 200])
这篇关于获取 Active Storage 变体的元数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!