Basics
class User < ApplicationRecord
has_one_attached :avatar
has_many_attached :documents
end
In order to do image processing you need to include MiniMagic gem
# Gemfile
# ...
gem 'mini_magick'
# ...
MiniMagic is a Ruby library that delegates commands to C program
ImageMagic. So it's
Rails > ActiveStorage > MiniMagic > ImageMagic
Therefore you need to have imagemagic installed !
<%= image_tag user.avatar.variant(resize: "200x150>") %>
Maning if I upload image
1000x500
I want it to be scaled up to200x150
maning the end image will be200x100
px
In Rails official guild you may find example:
<%= image_tag user.avatar.variant(resize_to_fit: [200, 150]) %>
Maning if I upload image
1000x500
I want it to be scaled to333X100
and then croped to fit200x100
px
This will not work in Rails 5.2 due to reason described here
Active Storage 5.2 still uses MiniMagick directly, so there are no #resize_* macros available there. The ImageProcessing addition to Active Storage was merged after 5.2 was released, so it's currently available only on GitHub and will be released in Active Storage 6.0. The mogrify command indicates that MiniMagick::Image class is used, as ImageProcessing gem uses convert.
workaround while ActiveStorage 6 is released:
head_image.variant(combine_options: {
auto_orient: true,
gravity: "center",
resize: "200x150^",
crop: "200x150+0+0"})
-
https://api.rubyonrails.org/classes/ActiveStorage/Variation.html
-
[representation](https://api.rubyonrails.org/classes/ActiveStorage/Blob/Representable.html#method-i-variant
blob.representation(resize: "100x100").processed.service_url
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
<CORSRule>
<AllowedOrigin>https://www.sajtka.com</AllowedOrigin>
<AllowedMethod>PUT</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
To allow only certain file types (source)
<AllowedOrigin>https://app.pobble.com</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<ExposeHeader>Accept-Ranges</ExposeHeader>
<ExposeHeader>Content-Range</ExposeHeader>
<ExposeHeader>Content-Encoding</ExposeHeader>
<ExposeHeader>Content-Length</ExposeHeader>
<ExposeHeader>Access-Control-Allow-Origin</ExposeHeader>
<AllowedHeader>*</AllowedHeader
-
https://edgeguides.rubyonrails.org/active_storage_overview.html
-
https://aws.amazon.com/premiumsupport/knowledge-center/s3-allow-certain-file-types/
Other articles
class Medium < ApplicationRecord
has_one_attached :image
validate :main_image_format
def main_image_format
return unless image.attached?
return if image.blob.content_type.in?(['image/jpeg', 'image/png'])
#image.purge_later
errors.add(:image, 'needs to be an PNG or JPEG image')
end