Skip to content

Crop the image

Masamoto Miyata edited this page Sep 1, 2018 · 12 revisions

We support the cropper for carrierwave_image.

First, you load javascript and css in you edit view. You must read both new and edit.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.1/cropper.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.1/cropper.js"></script>
<%= render 'dynamic_scaffold/bootstrap/edit' %>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.1/cropper.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.1/cropper.js"></script>
<%= render 'dynamic_scaffold/bootstrap/new' %>

Then pass the options of cropper to item method in your controller.

class ShopController < ApplicationController
  include DynamicScaffold::Controller
  dynamic_scaffold Shop do |config|

    config.form.item(
      :carrierwave_image,
      :image,
      cropper: { aspectRatio: 16.0 / 9.0, }
    )

And, mount image uploader and add virtual attribute cropper_{attribute_name} to model,

class Shop < ApplicationRecord
  mount_uploader :image, ShopImageUploader
  attr_accessor :cropper_image

And, add the process to the uploader. We have set cropper information in the model 'cropper_ [column_name]` attribute with JSON format.

class ShopImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  process :crop

  def crop
    if model.cropper_image
      detail = JSON.parse(model.cropper_image)
      manipulate! do |img|
        img.crop("#{detail['width']}x#{detail['height']}+#{detail['x']}+#{detail['y']}")
        img
      end
    end
  end