[Java] [Rails] Implementation of image preview function

1 minute read

Target

ezgif.com-video-to-gif.gif

Development environment

・ Ruby: 2.5.7
Rails: 5.2.4
・ Vagrant: 2.2.7
-VirtualBox: 6.1
・ OS: macOS Catalina

Premise

The following has been implemented.

Slim introduction
Introduction of Bootstrap3
Introduction of Font Awesome
-Login function implementation
Implementation of posting function

Implementation

1. Edit the view

slim:users/edit.html.slim


/Postscript
= f.file_field :profile_image, class: 'img_field', style: 'display:none;'
= attachment_image_tag @user, :profile_image, fallback: 'no-image.png', onClick: "$('.img_field').click()", class: 'center-block img-thumbnail img-responsive img_prev'
br

[Explanation]

(1) Hide file_field from display: none and assign a class.

= f.file_field :profile_image, class: 'img_field', style: 'display:none;'

(2) When the HTML (file_field) of the class assigned in (1) is clicked, JavaScript processing is executed.

onClick: "$('.img_field').click()"

2. Edit ʻapplication.scss`

appliacation.scss


//Postscript
.img_prev:hover {
  cursor: pointer; 
  opacity: 0.7;
  transform: scale(1.01, 1.01);
}

[Explanation]

① Reflect CSS when the mouse is on the image.

.img_prev:hover {}

② Change the mouse cursor to a pointer.

cursor: pointer; 

③ Lower the opacity and make the image a little whiter.

opacity: 0.7;

④ Enlarge the image a little.

transform: scale(1.01, 1.01);

3. Create / edit JavaScript file

Terminal


$ touch app/assets/javascripts/image_preview.js

image_preview.js


$(function () {
  function readURL(input) {
    if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function (e) {
        $('.img_prev').attr('src', e.target.result);
      }
      reader.readAsDataURL(input.files[0]);
    }
  }

  $('.img_field').change(function () {
    readURL(this);
  });
});

[Explanation]

(1) 1. The process of editing the view with (2).

$('.img_field').change(function () {
  readURL(this);
});