Bucket Place/Ruby on Rails

[Ruby on Rails] 이미지 URL 이용하여 resize하고 s3에 upload하기

Cloud Travel 2014. 8. 7. 14:36


이 글이 필요하신 분...


 1. URL로 가져온 이미지를 S3로 업로드 하고 싶다. 

 2. 추가적으로 나는 resize도 하고 싶다.


이 글은 최적의 방법은 아님을 작성하기 전에 미리 알려드립니다. 제가 아는 최적의 방법은 paperclip을 이용하여 thumbline을 구성하는 것입니다. 하지만, 이미 누군가 저질러놓은 잘못에 적용하기 위해서 이 방법을 체택하였습니다.



1) 필요한 Gem

 - gem 's3'

 - gem 'mini_magick'

 - gem 'open_uri_redirections' // FACEBOOK 이미지를 사용하는 경우


2) 구현 단계 1. 필요한 파일 require 추가

    require 'open-uri'

    require 's3'


3) 구현 단계 2. S3 연동/접속

    amazon = S3::Service.new(access_key_id: 'Your access key', secret_access_key: 'Your secret key')

    bucket = amazon.buckets.find('Your bucket name')

 

4) 구현 단계 3. open uri / mini magick으로 이미지 다운 받아서 가져오기

       image = MiniMagick::Image.open(uri)


5) 구현 단계 3-1. option 필요하다면 resize하기

      image_width = image[:width].to_f

      image_height = image[:height].to_f

      image_ratio = image_height / image_width;


      # Save original image

      size = image_width.to_s + "x" + image_height.to_s

      image.resize size

      image.write(Rails.root.join('public', 'tmp', file_name))   # Save image temporary position in public 

      file = bucket.objects.build("{S3 folder position}" + file_name) # S3 file create

      file.content = open(Rails.root.join('public', 'tmp', file_name)) # S3 file content load

      file.save  # S3 Save


      # Save medium image

      medium_width = 600;

      medium_height = 600 * image_ratio;

      image.resize medium_width.to_s + "x" + medium_height.to_s

      image.write(Rails.root.join('public', 'tmp', file_name))   # Save image temporary position in public 

      file = bucket.objects.build("{S3 folder position}" + "medium_" + file_name) # S3 file create

      file.content = open(Rails.root.join('public', 'tmp', file_name)) # S3 file content load

      file.save  # S3 Save


 6) 구현 단계 4. temporary image 삭제

File.delete(Rails.root.join('public', 'tmp', file_name));



만약, 페이스북이미지를 resize해서 저장할 필요가 있다면... 

페이스북 이미지는 한번에 바로 가져오는 것이 아니라 redirect 주소가 필요합니다. redirect주소를 알아오기 위해서는 맨위에서 말했듯이 open_uri_redirections가 필요합니다.


facebook profile image 가져오는 방법


require 'open_uri_redirections'

      require 'open-uri'

      require 's3'


open(auth.info.image, :allow_redirections => :safe) do |r|

          @profile_uri = r.base_uri

        end


가져오신 url을 가지고 위와 같은 일을 한번더 해주시면 된답니다!