How to write to tmp file or image object stream up to s3 in ruby ​​on rails

The code below resizes my image. But I'm not sure how to write it to a temp or blob file so that I can upload it to s3.

origImage = MiniMagick::Image.open(myPhoto.tempfile.path) origImage.resize "200x200" thumbKey = "tiny-#{key}" obj = bucket.objects[thumbKey].write(:file => origImage.write("tiny.jpg")) 

I can only download the source file to s3 with the following command:

 obj = bucket.objects[key].write('data') obj.write(:file => myPhoto.tempfile) 

I think I want to create a temporary file, read the image file and load it:

  thumbFile = Tempfile.new('temp') thumbFile.write(origImage.read) obj = bucket.objects[thumbKey].write(:file => thumbFile) 

but the origImage class does not have a read command.

UPDATE: I read the source code and found out about this command

 # Writes the temporary file out to either a file location (by passing in a String) or by # passing in a Stream that you can #write(chunk) to repeatedly # # @param output_to [IOStream, String] Some kind of stream object that needs to be read or a file path as a String # @return [IOStream, Boolean] If you pass in a file location [String] then you get a success boolean. If its a stream, you get it back. # Writes the temporary image that we are using for processing to the output path 

And s3 api docs say that you can transfer content using a code block, for example:

 obj.write do |buffer, bytes| # writing fewer than the requested number of bytes to the buffer # will cause write to stop yielding to the block end 

How do I change my code so that

origImage.write (here s3stream)

http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/S3/S3Object.html

UPDATE 2

This code successfully uploads a thumbnail file to s3. But I will still love how to do it. I think it would be much more effective.

  #resize image and upload a thumbnail smallImage = MiniMagick::Image.open(myPhoto.tempfile.path) smallImage.resize "200x200" thumbKey = "tiny-#{key}" newFile = Tempfile.new("tempimage") smallImage.write(newFile.path) obj = bucket.objects[thumbKey].write('data') obj.write(:file => newFile) 
+4
source share
2 answers

smallImage.to_blob ?

below is a copy of the code from https://github.com/probablycorey/mini_magick/blob/master/lib/mini_magick.rb

  # Gives you raw image data back # @return [String] binary string def to_blob f = File.new @path f.binmode f.read ensure f.close if f end 
0
source

Have you looked at paperclip gem? The gem offers direct s3 compatibility and works great.

-1
source

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


All Articles