Rails: upload images from S3, resize and upload back to S3

In my Rails 4 application, I have a large number of images stored on S3 using the Clip program. The image URL looks like http://s3.amazonaws.com/bucketname/files/images/000/000/012/small/image.jpg?1366900621 .

Given the following investment class:

  • How to download images from S3 and save them locally?
  • Then how to resize a locally saved image
  • Load the modified image into another S3 bucket without Paperclip (along the path s3 / newbucket / images / {: id} / {imagesize.jpg})

Attachment Class:

class Image < ActiveRecord::Base
  has_attached_file :file, styles: { thumbnail: '320x320', icon: '64x64', original: '1080x1080' }
  validates_attachment :file, presence: true, content_type: { content_type: /\Aimage\/.*\Z/ }
end
+4
source share
1 answer

" ", , . , , .

, , .

def download_from_s3 url_to_s3, filename
  uri = URI(url_to_s3)
  response = Net::HTTP.get_response(uri)
  File.open(filename, 'wb'){|f| f.write(response.body)}
end

, URL, . ( , Paperclip). image-magick convert script. 30:

convert  -strip -geometry 30 -quality 100 -sharpen 1 '/photos/aws_images/000/000/015/original/index.jpg' '/photos/aws_images/000/000/015/original/S_30_WIDTH__q_100__index.jpg' 2>&1 > /dev/null

convert , , , ! gem, , , convert.

- S3 bucket. , aws-sdk gem AWS::S3 ( ).

def upload_to_s3 bucket_name, key, file
  s3 = AWS::S3.new(:access_key_id => 'YOUR_ACCESS_KEY_ID', :secret_access_key => 'YOUR_SECRET_ACCESS_KEY')
  bucket = s3.buckets[bucket_name]
  obj = bucket.objects[key]
  obj.write(File.open(file, 'rb'), :acl => :public_read)
end

, AWS::S3 S3, . , ( , , ).

+1

All Articles