Rails 5.2 ActiveStorage save and then read Exif da

2020-04-11 06:27发布

问题:

On Rails 5.2 I am trying to save an avatar via ActiveStorage but it seems as though not image oriantation data is being saved in the active storage blob.

I am saving the avatar via a file_field on a create action my

#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

I have been reading some documentation for minimagick https://github.com/minimagick/minimagick but have not figured out how I can associate

user.avatar.blob 

with

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

I have tried

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

but have had no luck

I need to try and figure this out because some avatars stored in active storage are being displayed rotated 90 degrees.

https://edgeguides.rubyonrails.org/active_storage_overview.html talks of image processing but I have also had no luck with the gem rails recommends

回答1:

I think you want to use a variant when displaying the image rather than trying to edit the stored image. To fix the orientation, you could say:

user.avatar.variant(auto_orient: true)

And if you want to do several operations at once (rather than in a pipeline), use combine_options:

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

The edited image will be cached so you only do the transformation work on first access. You might want to put your variants into view helpers (or maybe even a model concern depending on your needs) so that you can isolate the noise.

You might want to refer to the API docs as well as the guide:

  • ActiveStorage::Variant
  • ActiveStorage::Variation