简体   繁体   中英

Allowing users to crop and resize images Ruby on Rails

Sorry for the fairly generic question but I was wondering whether anyone had any recommendations on how to best allow users to crop and edit their own images.

What I would like to happen is that when a user uploads their image on my app for the app to show a copy of the image with an overlay that only allows a fixed aspect ratio (perhaps 4:3), the user would then be able to select the area of the image they would like to crop and save as their image.

The best example I can think of this is when cropping cover photos on Facebook.

I have looked into the various Gems and elements that I believe would be needed as below:

Carrierwave - For file uploading (and I think cropping - correct me if I am wrong) ImageMagick/Mini-Magick/Rmagick - to handle processing the image.

However I am still a little unsure how these fit together.

Any advice people have on the best combination of gems and how they work together to achieve this cropping feature would be much appreciated.

https://github.com/awijeet/Image_cropping_in_rails4

Here I have implemented that in Rails 4, let me known if you need more clarification on it.

Thank you.

有一个非常好的教程,通过示例解释了多个图像上传和裁剪轨道

To reproduce the example you point out, you will need a front-end part and a back-end part.

Front-End

So to achieve that you need some front-end interactive tool. There are plenty out there, like Cropper.js or Croppie .

Back-End with 3rd party gems

Once you receive the file, and the coordinate on how to crop the image, Carrierwave + ImageMagick will work.

Back-End with ActiveStorage

In Rails 5+,Active Storage is also absolutely able to do that with the variant method .

For instance, you have a model with an attachment photo .

class User < ActiveRecord
  has_one_attached :photo
end

Then, in your controller, in the method receiving the POST, if you were using Cropper.js for instance:

def add_picture
  @user.update(params.require(:user).permit(:photo))
  @user.photo.variant(crop: cropping_dimensions)
end

private

def cropping_dimensions
  received = JSON.parse(params[:cropping])
  sprintf(
    "%fx%f%+f%+f",
    received[:width],
    received[:height],
    received[:x],
    received[:y]
  )
end

Active Storage variant method uses Vips by default in Rails 7.

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