[RUBY] How to implement a circular profile image in Rails using CarrierWave and R Magick

What is Carrierwave?

It is a gem that allows you to easily add an image file upload function.

What is RMgick

You can change the size of the image file and crop the center of the image. Even a rectangular image can be made into a beautiful square image. (Because it can be extracted from the center with the specified size)

version

Ruby 2.7.0 Rails 6.0.2.1 carrierwave 2.1.0 rmagick 4.0.0

Step 1 ・ Introduce Carrierwave

First, install the following gem

Gemfile.


gem 'carrierwave'

Then do bundle install. Then create an uploader with rails g uploader image.

Terminal.


$ bundle install

$ rails g uploader image

app/uploaders/image_uploader.rb //The file will be created

If you don't have an image column, you have to create one. Since this is a profile image, I will create it in the user model.

Terminal.


$ rails g migration AddImageToUsers image:string

$ rails db:migrate

You now have an image column in your user model.

Next, edit ʻuser.rb of the added user model and describe ʻimage_uploader.

user.rb


class User < ApplicationRecord
  #abridgement

  mount_uploader :image, ImageUploader #add to
end

This completes the introduction of CarrierWave.

Step 2-Introduce R Magic

First of all, the introduction of R Magick is very complicated. Lol However, please be assured that if you do it in order, you can install it without any problems.

First of all, install ImageMagick 6 and pkg-config. Execute the following in order.

Terminal.


$ brew install imagemagick@6

$ brew install pkg-config

Then do the following

Terminal.


$ export PKG_CONFIG_PATH=/usr/local/opt/imagemagick@6/lib/pkgconfig

Finally, use the gem command to install rmagick.

Terminal.


$ gem install rmagick

Now you are finally ready to install the gem. Add the following to Gemfile.

Gemfile.


gem 'rmagick'

Run bundle install

Terminal.


$ bundle install

This completes the introduction of R Magick.

Step 3 ・ Describe in ʻimage_uploader.rb`

Describe the following in the file ʻimage_uploader.rb` created at the beginning

image_uploader.rb


  version :thumb do
    process :resize_to_fill => [width, height, gravity = ::Magick::CenterGravity]
  end

  #Enter the width and height values for width and height, respectively. If you enter the same number, it will be a square.
  #In the case of the example below, it will be a 200px square.
  #[Example]
  #version :thumb do
    #process :resize_to_fill => [200, 200, gravity = ::Magick::CenterGravity]
  #end

You can now make the image square.

Next, write a description to prevent image inversion.

image_uploader.rb


class ImageUploader < CarrierWave::Uploader::Base
  #abridgement

  def auto
    manipulate! do|image|
      image.auto_orient
    end
  end

  process :auto

 #abridgement
end

Step 4 ・ Model description

This time it is a profile picture of the user, so I will describe it in the user model.

user.rb


class User < ApplicationRecord
  #abridgement

  mount_uploader :image, ImageUploader
end

The model is now associated.

Step 5 ・ Description of controller

Next, write it in the controller.

users_controller.rb


class UsersController < ApplicationController
  #abridgement

  def show
    @user = User.find(params[:id])
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    if @user.id == current_user.id
      @user.update(user_params)
      flash[:success] = "Your profile has been updated!"
      redirect_to user_path(@user)
    else
      render 'edit'
    end
  end

  private

  def user_params
    params.require(:user).permit(:name, :email, :image)
  end 
end

Step 6 ・ Implementation of view

Next, we will implement it in the view.

erb:edit.html.erb


 <% if @user.image? %>
   <%= image_tag @user.image.thumb.url, class: "user-icon" %>
 <% else %>
   <%= image_tag "default.jpg ", alt: "user-icon", size: "200", class: "user-icon" %>
 <% end %>
 <button type="button" class="btn btn-outline-secondary rounded-pill">
   <%= f.file_field :image, accept: 'image/jpeg,image/gif,image/png', class: "image-select-btn" %>
 </button>

If you have uploaded a profile picture with <% if @ user.image?%>, It will be displayed, otherwise the default image will be displayed. Put the default images in ʻapp / assets / images`.

By the way

erb:edit.html.erb


<%= image_tag "/assets/images/default.jpg ", alt: "user-icon", size: "200", class: "user-icon" %>

Please note that an error will occur if you write.

Return to the explanation of ʻedit.html.erb`.

By writing thumb on the second line, the contents (width and height) described earlier in ʻimage_uploader.rb` will be reflected in the image.

Then use CSS to round the image.

users.scss


.user-icon {
  border-radius: 100px;
}

You have now rounded your profile picture.

If the profile image has not been uploaded, the implementation below is possible.

スクリーンショット 2020-09-03 9.30.11.png

You can upload your profile picture from the "Select File" button above.

When uploaded, it will be circular like the default image.

This is the end of implementation.

Reference material

I wrote it with reference to the following article. Thank you to everyone who posted the article.

Introduce image upload Carrierwave Using RMagick with Rails [Rails] Create thumbnails with Carrier Wave and R Magick Use CarrierWave to set user images.

Recommended Posts

How to implement a circular profile image in Rails using CarrierWave and R Magick
How to implement image posting using rails
How to implement a like feature in Rails
How to implement a slideshow using slick in Rails (one by one & multiple by one)
How to implement a like feature in Ajax in Rails
How to convert A to a and a to A using AND and OR in Java
How to implement image posting function using Active Storage in Ruby on Rails
[Rails] A simple way to implement a self-introduction function in your profile
[Rails] How to upload images to AWS S3 using Carrierwave and fog-aws
How to implement UI automated test using image comparison in Selenium
How to implement search functionality in Rails
How to insert a video in Rails
How to implement ranking functionality in Rails
How to create a query using variables in GraphQL [Using Ruby on Rails]
[Rails] How to create a graph using lazy_high_charts
[Rails] How to upload multiple images using Carrierwave
How to easily create a pull-down in Rails
How to make a follow function in Rails
A memo to simply create a form using only HTML and CSS in Rails 6
How to implement guest login in 5 minutes in rails portfolio
How to write a date comparison search in Rails
Rails learning How to implement search function using ActiveModel
[Rails] How to load JavaScript in a specific view
[Rails] How to display an image in the view
[Rails] How to install a decorator using gem draper
Try to implement tagging function using rails and js
Implement a reservation system using Rails and simple calendar! Let's add validation to datetime!
[Rails] How to implement scraping
How to set and describe environment variables using Rails zsh
How to deploy jQuery in your Rails app using Webpacker
[Rails] How to delete images uploaded by carrierwave (using devise)
How to display a graph in Ruby on Rails (LazyHighChart)
How to develop and register a Sota app in Java
How to join a table without using DBFlute and sql
[Rails] How to write in Japanese
[Rails 6] How to create a dynamic form input screen using cocoon
How to POST JSON in Java-Method using OkHttp3 and method using HttpUrlConnection-
[Webpacker] Summary of how to install Bootstrap and jQuery in Rails 6.0
How to implement a job that uses Java API in JobScheduler
How to set and use profile in annotation-based Configuration in Spring framework
How to delete large amounts of data in Rails and concerns
Implement a contact form in Rails
How to introduce jQuery in Rails 6
[Rails] How to implement star rating
How to rename a model with foreign key constraints in Rails
[Reading impression] "How to learn Rails, how to write a book, and how to teach"
[rails6.0.0] How to save images using Active Storage in wizard format
How to install Swiper in Rails
[Ruby on Rails] How to log in with only your name and password using the gem devise
How to set an image in the drawable Left / Right of a button using an icon font (Iconics)
How to build a Ruby on Rails environment using Docker (for Docker beginners)
[Rails] How to log in with a name by adding a devise name column
How to implement more than one top page in Rails breadcrumb trail
How to implement gem "summer note" in wysiwyg editor in Ruby on Rails
How to update user edits in Rails Devise without entering a password
[Docker] How to create a virtual environment for Rails and Nuxt.js apps
[Rails] How to create a table, add a column, and change the column type
[Swift] How to set an image in the background without using UIImageView.
How to execute a contract using web3j
How to sort a List using Comparator
How to implement Kalman filter in Java