Rails: crop images using the porch, S3 and RMagick

I am currently trying to encode a custom cropping system similar to others on the Internet, where the user can select the cropping area and then crop the image accordingly. The application is in Rails, and we use Paperclip with Amazon S3 to store files. I'm in a lot of trouble, although I want RMagick to trim the S3 file accordingly. Here is the current code (which does not work):

   if params[:width].to_i > 0 and params[:height].to_i > 0 then
      photo = Photo.find(params[:id])
      image_data = Net::HTTP.get_response(URI.parse(photo.photo.url(:big))).body
      orig_img = Magick::ImageList.new
      orig_img.from_blob(image_data)

      args = [params[:x1].to_i, params[:y1].to_i, params[:width].to_i, params[:height].to_i]
      orig_img.crop!(*args)
      photo.update_attributes({:photo => orig_img.to_blob})

      photo.photo.reprocess!
      photo.save
    end

The main problem is that the cropped image does not load back to S3 through a paper clip and therefore is not cropped correctly. Has anyone tried something like this with a paper clip before? It may not even be possible, but any help would be greatly appreciated.

+3
3

:

  photo = Photo.find(params[:id])
  image_data = Net::HTTP.get_response(URI.parse(photo.photo.url(:big))).body
  orig_img = Magick::ImageList.new
  orig_img.from_blob(image_data)

  args = [params[:x1].to_i, params[:y1].to_i, params[:width].to_i, params[:height].to_i]
  orig_img.crop!(*args)

  tmp_img = Tempfile.new("image_data")
  orig_img.format = "png"
  tmp_img.write(orig_img.to_blob)
  photo.photo = tmp_img
  tmp_img.close

  photo.photo.reprocess!
  photo.save

, , , . , , .

EDIT: , Tempfile paperclip.

+5

attr_accessors . .

class Poodle < ActiveRecord::Base
  has_attached_file :avatar, :styles => Proc.new{|a| a.instance.get_styles}
  attr_accessor :width, :height


  def get_styles(style = "medium")
    return {style.to_sym => [self.width, self.height].join("x") + ">" }
  end
 end
0

, " " .

, .

0
source

Source: https://habr.com/ru/post/1704367/


All Articles