Simply put, it's a Rails library (gem) that makes it easy to add image upload functionality. You can specify the size of the image to upload.
The posted images will be accumulated under the public of the application. If you don't need to manage your images on GitHub, add a description to .gitignore as below Don't manage it with Git.
# .Add to gitignore
public/uploads/*
Execute in order from the top.
#Run in terminal
$ brew install imagemagick
#Add to Gemfile
gem 'carrierwave'
gem 'mini_magick'
#Run in terminal
$ bundle install
#Run in terminal
$ rails g uploader image
# app/models/Post model.Edit rb
mount_uploader :image, ImageUploader
# app/uploaders/image_uploader.Edit rb
class ImageUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
include CarrierWave::MiniMagick
# storage :fog
#~abridgement~
process resize_to_fit: [800, 800]
#~abridgement~
end
After running "brew install imagemagick", let's install the required gems. Add "carrierwave" and "minimagick" to the Gemfile and run bundle install from the terminal.
Next, let's create an image uploader. In the terminal, running the "rails g uploader image" command will create image_uploader.rb under the app / uploaders directory.
After creating the uploader, edit the model related to the post and describe to mount "image_uploader".
Finally, let's edit image_uploader.rb so that we can resize the image via MiniMagick. Uncomment "include CarrierWave :: MiniMagick" on line 5.
After that, add "process resize_to_fit: [vertical size, horizontal size]" to any place. (Size is arbitrary) resize_to_fit means to resize the aspect within the specified size while maintaining the aspect ratio.
Recommended Posts