简体   繁体   中英

Paperclip conditional styles

From upload.html.erb I am submitting a form with data - including an image and crop information (x and y coordinates, width and height) - to a controller method called update_image . I then want to pass this information on over to the model ( picture.rb ) and save a cropped version of this image.

I'm using Rails 5 and Paperclip to store images. I've ran into the following two problems which I don't seem to be able to solve:

  1. How to access the crop information data inside my model? I don't want to save the crop information in the database.
  2. How to crop images only if crop information is present? (I want to use the same model for regular file uploads from another form that doesn't have the crop functionality)

Help is greatly appreciated!

upload.html.erb

<form action="/update_image" enctype="multipart/form-data" accept-charset="UTF-8" method="post">
  <input type="file" name="image" />
  <input type="hidden" name="crop_x" value="0" />
  <input type="hidden" name="crop_y" value="5" />
  <input type="hidden" name="crop_width" value="200" />
  <input type="hidden" name="crop_height" value="100" />
</form>

upload_controller.rb

def update_image
  picture = Picture.new(image: params[:image])
end

picture.rb

class Picture < ActiveRecord::Base
  has_attached_file :image, styles: {
    cropped: "-crop #{@crop_w}x#{@crop_h}+#{@crop_x}+#{@crop_y}",
    thumb: "100x100>"
  }
end

You are looking for dynamic styles.

class Picture < ActiveRecord::Base
  attr_accessor :crop_needed
  has_attached_file :image, styles: Proc.new { |clip| clip.instance.attachment_sizes }

 def attachment_sizes
    crop_needed ? {
      cropped: "-crop #{@crop_w}x#{@crop_h}+#{@crop_x}+#{@crop_y}",
      thumb: "100x100>"
    } : {thumb: "100x100>"}
 end
end

From the controller where you need cropping:

def update_image
  picture = Picture.new
  picture.crop_needed = true if params[:crop_x].present?
  picture.image = params[:image]
  picture.save
end

From the other controller where you do not need cropping, just set crop_needed to false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM