ruby-on-rails ActiveStorage -上传后获取图像尺寸

cvxl0en2  于 2023-03-20  发布在  Ruby
关注(0)|答案(3)|浏览(174)

我正在使用Rails + ActiveStorage上传图片文件,希望在上传后将宽度和高度保存在数据库中,但是我在任何地方都找不到这样的例子。
这是我从各种API文档中拼凑出来的,但最终出现了以下错误:将blob替换为image.file会导致rails记录“跳过图像分析,因为ImageMagick不支持该文件”(https://github.com/rails/rails/blob/master/activestorage/lib/active_storage/analyzer/image_analyzer. rb#L39)。
代码:

class Image < ApplicationRecord
  after_commit { |image| set_dimensions image }

  has_one_attached :file

  def set_dimensions(image)
    if (image.file.attached?)
      blob = image.file.download

      # error: private method `open' called for #<String:0x00007f9480610118>
      meta = ActiveStorage::Analyzer::ImageAnalyzer.new(blob).metadata
    end
  end
end

这种方法也存在问题,因为在destroy时也调用了after_commit

**TLDR:**是否有一种“正确”的方法可以在上传后立即获取图像元数据?

u4vypkhs

u4vypkhs1#

解决方案内置导轨

根据ActiveStorage概述指南,已有一个使用ActiveStorage::Analyzer::ImageAnalyzer的现有解决方案image.file.analyzeimage.file.analyze_laterdocs
根据#analyze docs
当新的blob第一次被附加时,它会通过analyze_later自动地进行异步分析。
这意味着您可以通过以下方式访问图像尺寸

image.file.metadata
#=> {"identified"=>true, "width"=>2448, "height"=>3264, "analyzed"=>true}

image.file.metadata['width']
image.file.metadata['height']

因此,您的模型可能如下所示:

class Image < ApplicationRecord
  has_one_attached :file

  def height
    file.metadata['height']
  end

  def width
    file.metadata['width']
  end
end

对于90%的常规情况,您可以很好地处理此问题

但是:问题是这是“异步分析”(#analyze_later),这意味着在上传后不会立即存储元数据

image.save!
image.file.metadata
#=> {"identified"=>true}
image.file.analyzed?
# => nil

# .... after ActiveJob for analyze_later finish
image.reload
image.file.analyzed?
# => true
#=> {"identified"=>true, "width"=>2448, "height"=>3264, "analyzed"=>true}

这意味着,如果您需要真实的访问宽度/高度(例如,API对新上传文件尺寸的响应),则可能需要执行以下操作

class Image < ApplicationRecord
  has_one_attached :file
  after_commit :save_dimensions_now

  def height
    file.metadata['height']
  end

  def width
    file.metadata['width']
  end

  private
  def save_dimensions_now
    file.analyze if file.attached?
  end
end

注:在作业中异步执行此操作是有原因的。由于需要执行此额外代码,请求的响应速度会稍慢。因此,您需要有“立即保存维”的好理由
此解决方案的镜像可在How to store Image Width Height in Rails ActiveStorage中找到

DIY解决方案

建议:不要这样做,依赖现有的VanillaRails解决方案

需要更新附件的型号

Bogdan Balan's solution将工作。下面是相同解决方案的重写,但没有skip_set_dimensions attr_accessor

class Image < ApplicationRecord
  after_commit :set_dimensions

  has_one_attached :file

  private

  def set_dimensions
    if (file.attached?)
      meta = ActiveStorage::Analyzer::ImageAnalyzer.new(file).metadata
      height = meta[:height]
      width  = meta[:width]
    else
      height = 0
      width  = 0
    end

    update_columns(width: width, height: height) # this will save to DB without Rails callbacks
  end
end

update_columns docs

不需要更新附件的型号

很有可能你正在创建一个模型,你想在其中存储文件附件,并且不再更新它。(所以如果你需要更新附件,你只需要创建新的模型记录并删除旧的)
在这种情况下,代码就更加流畅了:

class Image < ApplicationRecord
  after_commit :set_dimensions, on: :create

  has_one_attached :file

  private

  def set_dimensions
    meta = ActiveStorage::Analyzer::ImageAnalyzer.new(file).metadata
    self.height = meta[:height] || 0
    self.width  = meta[:width] || 0
    save!
  end
end

您可能希望在保存之前验证附件是否存在。

class Image < ApplicationRecord
  after_commit :set_dimensions, on: :create

  has_one_attached :file

  # validations by active_storage_validations
  validates :file, attached: true,
    size: { less_than: 12.megabytes , message: 'image too large' },
    content_type: { in: ['image/png', 'image/jpg', 'image/jpeg'], message: 'needs to be an PNG or JPEG image' }

  private

  def set_dimensions
    meta = ActiveStorage::Analyzer::ImageAnalyzer.new(file).metadata
    self.height = meta[:height] || 0
    self.width  = meta[:width] || 0
    save!
  end
end
测试
require 'rails_helper'
RSpec.describe Image, type: :model do
  let(:image) { build :image, file: image_file }

  context 'when trying to upload jpg' do
    let(:image_file) { FilesTestHelper.jpg } # https://blog.eq8.eu/til/factory-bot-trait-for-active-storange-has_attached.html

    it do
      expect { image.save }.to change { image.height }.from(nil).to(35)
    end

    it do
      expect { image.save }.to change { image.width }.from(nil).to(37)
    end

    it 'on update it should not cause infinitte loop' do
      image.save! # creates
      image.rotation = 90 # whatever change, some random property on Image model
      image.save! # updates
      # no stack ofverflow happens => good
    end
  end

  context 'when trying to upload pdf' do
    let(:image_file) { FilesTestHelper.pdf } # https://blog.eq8.eu/til/factory-bot-trait-for-active-storange-has_attached.html

    it do
      expect { image.save }.not_to change { image.height }
    end
  end
end

文章attaching Active Storange to Factory Bot解释了FilesTestHelper.jpg的工作原理

vuktfyat

vuktfyat2#

回答自己的问题:我最初的解决方案很接近,但是需要安装ImageMagick(它没有安装,错误消息也没有指出这一点)。

class Image < ApplicationRecord
  attr_accessor :skip_set_dimensions
  after_commit ({unless: :skip_set_dimensions}) { |image| set_dimensions image }

  has_one_attached :file

  def set_dimensions(image)
    if (Image.exists?(image.id))
      if (image.file.attached?)
        meta = ActiveStorage::Analyzer::ImageAnalyzer.new(image.file).metadata

        image.width = meta[:width]
        image.height = meta[:height]
      else
        image.width = 0
        image.height = 0
      end

      image.skip_set_dimensions = true
      image.save!
    end
  end
end

我还使用this technique跳过save!上的回调,防止无限循环。

fumotvh3

fumotvh33#

我想你可以在更新之前从javascript中获取维度,然后将这些数据发布到controller中。你可以检查一下:Check image width and height before upload with Javascript

相关问题