首页 > 解决方案 > Rails 5.2 ActiveStorage 保存然后读取 Exif 数据

问题描述

在 Rails 5.2 上,我试图通过 ActiveStorage 保存头像,但似乎没有图像方向数据保存在活动存储 blob 中。

我通过创建操作上的 file_field 保存头像

#user model 

has_one_attached :avatar

private

def avatar_validation
  if avatar.attached?
    if avatar.blob.byte_size > 1000000
      avatar.purge
      errors.add(:avatar, 'file is too large')
    elsif !avatar.blob.content_type.in?(%w[image/png image/jpg 
          image/jpeg])
      avatar.purge
      errors.add(:avatar, 'file type needs to be JPEG, JPG, or PNG')
    end
  end
end

我一直在阅读 minimagick https://github.com/minimagick/minimagick的一些文档,但还没有弄清楚如何关联

user.avatar.blob 

image = MiniMagick::Image.open("input.jpg")

我试过了

image = MiniMagick::Image.open("user.avatar.blob")

但没有运气

我需要尝试解决这个问题,因为存储在活动存储中的一些头像正在旋转 90 度显示。

https://edgeguides.rubyonrails.org/active_storage_overview.html 谈论图像处理,但我也没有运气推荐的 gem rails

标签: ruby-on-railsrubyimage-processingrails-activestorageminimagick

解决方案


我认为您想在显示图像时使用变体,而不是尝试编辑存储的图像。要固定方向,您可以说:

user.avatar.variant(auto_orient: true)

如果您想一次执行多个操作(而不是在管道中),请使用combine_options

user.avatar.variant(combine_options: {
  auto_orient: true,
  gravity:     'center',
  resize:      '23x42',    # Using real dimensions of course.
  crop:        '23x42+0+0'
})

编辑后的图像将被缓存,因此您只需在首次访问时进行转换工作。您可能希望将您variant的 s 放入视图助手(或者根据您的需要甚至可能是模型问题),以便您可以隔离噪音。

您可能需要参考 API 文档和指南:


推荐阅读