繁体   English   中英

Attachment_fu旋转S3存储导轨中的图像

[英]Attachment_fu rotate image in S3 storage Rails

如何旋转S3存储中的图像,我正在使用Attachment_fu和Amazon S3,我想实现一项功能,该功能允许用户通过将现有图像旋转90度来编辑现有图像。 我想知道是否有人玩过这个游戏,或者有什么想法。 我目前正在使用rmagick旋转Rails目录中的图像。 但是在AWS S3中,存储无法旋转图像。

require 'RMagick'

def rotate
    photo   = Photo.find(params[:id])
    image   = Magick::ImageList.new(photo.file)
    image   = image.rotate(90)
    image.write(photo.file)
end

我正在使用这个宝石:

gem 'pothoven-attachment_fu'
gem 'aws-s3'
gem 'rmagick'

我解决了这个问题。

def update_photo
      require 'RMagick'
      require 'base64'

      # get the image data in Photo table
      @photo = Photo.where(id: params[:photo_id]).first

      # get image path in S3 url and encode to Base64 binary
      img_url = @photo.s3_url()
      img_uri = URI.parse(img_url)
      base64_image = Base64.encode64(open(img_uri) { |io| io.read })
      image_file_name = File.basename(img_uri.path,File.extname(img_uri.path))
      filename_path = "#{Rails.root.to_s}/tmp/#{image_file_name}"

      # create tempfile in rails root/tmp folder and decode the Base64 binary into image file, then processing RMagick to rotate the image into desire image rotation.
      @tempfile = Tempfile.new(filename_path)
      @tempfile.binmode
      @tempfile.write Base64.decode64(base64_image)
      @tempfile.close

      # rotate image using RMagick
      Magick::Image.read(img_uri).first.rotate!(params[:photo_degree].to_i).write(@tempfile.path)

      # for security we want the actual content type, not just what was passed in
      # get mime type of image and passed into ActionDispatch type
      content_type = `file --mime -b #{@tempfile.path}`.split(";")[0]

      # we will also add the extension ourselves based on the above
      # if it's not gif/jpeg/png, it will fail the validation in the upload model
      extension = content_type.match(/gif|jpeg|png/).to_s
      extension = "jpg" if extension == "jpeg"

      # append filename to prevent browser image caching
      filename_path += "_#{params[:photo_degree]}"

      filename_path += ".#{extension}" if extension

      # passed the data into  Rails core ActionDispatch instead of file input object
      file = ActionDispatch::Http::UploadedFile.new({
        tempfile: @tempfile,
        type: content_type,
        filename: filename_path
      })

      # delete the existing image
      @photo.destroy 

      # create new image
      img_rotate                = Photo.new()
      img_rotate.id             = @photo.id
      img_rotate.uploaded_data  = file
      img_rotate.save

       ensure
          clean_tempfile

end

  def clean_tempfile
    if @tempfile
      @tempfile.close
      @tempfile.unlink
    end
  end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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