#前提・実現したいこと
Rails 5 でユーザー投稿型サービスを開発しています。
投稿作成画面で、ユーザーが画像を自由に選択しトリミングした上で投稿できるようにしたいです。
以下の記事を参考に作っています。
CarrierwaveとMiniMagickでユーザー任意の入力値で画像をトリミングする
Upload image crop with Ruby and Rails, CarrierWave and Cropper.js
#発生している問題
投稿は作成されるのですが、画像がトリミングされず、もとのままアップされてしまいます。
フロントからデータの送信は無事にされているので、アップローダ内のcropメソッドに不備があるのだと思いますが、はっきりと分からず困っています…
#該当のソースコード
サーバーサイド
javascript
1 ... 2 $('#_submit').on('click', function(){ 3 // crop のデータを取得 4 var data = $('#crop_img').cropper('getData'); 5 $("#post_image_x").val(Math.round(data.x)); 6 $("#post_image_y").val(Math.round(data.y)); 7 $("#post_image_w").val(Math.round(data.width)); 8 $("#post_image_h").val(Math.round(data.height)); 9 $("#myform").submit(); 10}); 11
Ruby
1class ItemImageUploader < CarrierWave::Uploader::Base 2 3 include CarrierWave::RMagick 4 include CarrierWave::MiniMagick 5 process :convert => 'jpg' 6 7 version :standard do 8 process :crop 9 process :resize_to_fill=> [570, 852, gravity = 'Center'] 10 end 11 12 # Choose what kind of storage to use for this uploader: 13 if Rails.env.development? 14 storage :file 15 elsif Rails.env.test? 16 storage :file 17 else 18 storage :fog 19 end 20 21 22 def store_dir 23 "post_images/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" 24 end 25 26 version :thumb do 27 process :crop 28 process :resize_to_fill=>[380, 568, gravity = 'Center'] 29 end 30 31 def extension_whitelist 32 %w(jpg jpeg gif png) 33 end 34 35 def crop 36 return if [model.image_x, model.image_y, model.image_w, model.image_h].all? 37 manipulate! do |img| 38 crop_x = model.image_x.to_i 39 crop_y = model.image_y.to_i 40 crop_w = model.image_w.to_i 41 crop_h = model.image_h.to_i 42 img.crop([[crop_w, crop_h].join('x'), [crop_x, crop_y].join('+')].join('+')) 43 img = yield(img) if block_given? 44 img 45 end 46 end 47 48 # Override the filename of the uploaded files: 49 # Avoid using model.id or version_name here, see uploader/store.rb for details. 50 def filename 51 "#{secure_token}.jpg" if original_filename.present? 52 end 53 54 protected 55 def secure_token 56 var = :"@#{mounted_as}_secure_token" 57 model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.uuid) 58 end 59 end
ruby
1class PostsController < ApplicationController 2 ... 3 def new 4 @post = Post.new 5 end 6 7 def create 8 post = params.require(:post).permit( 9 :designer_id, 10 {image_name: []}, 11 :image_x, 12 :image_y, 13 :image_w, 14 :image_h, 15 :detail 16 ) 17 @post = Post.new(post) 18 if @post.save 19 ... 20 end 21 end 22... 23end
ruby
1class Post < ApplicationRecord 2 mount_uploaders :image_name, ItemImageUploader 3 serialize :image_name, JSON 4 # crop用の仮想attribute 5 attr_accessor :image_x 6 attr_accessor :image_y 7 attr_accessor :image_w 8 attr_accessor :image_h 9 ... 10end 11
回答1件
あなたの回答
tips
プレビュー