如何在Rails中的ruby中写入tmp文件或将图像对象流化到s3

Chi*_*Fur 5 ruby-on-rails image-processing amazon-s3

下面的代码调整了我的图像大小。但是我不确定如何将其写到临时文件或Blob中,因此我可以将其上传到s3。

  origImage = MiniMagick::Image.open(myPhoto.tempfile.path)
  origImage.resize "200x200"
  thumbKey = "tiny-#{key}"

  obj = bucket.objects[thumbKey].write(:file => origImage.write("tiny.jpg"))
Run Code Online (Sandbox Code Playgroud)

我可以使用以下命令将原始文件上传到s3:

obj = bucket.objects[key].write('data')
obj.write(:file => myPhoto.tempfile)
Run Code Online (Sandbox Code Playgroud)

我想我想创建一个临时文件,将图像文件读入其中并上传:

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

但是origImage类没有读取命令。

更新: 我正在阅读源代码,并发现有关写命令的信息

# 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
Run Code Online (Sandbox Code Playgroud)

s3 api文档说,您可以使用以下代码块来流式传输内容:

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
Run Code Online (Sandbox Code Playgroud)

我该如何更改代码

origImage.write(此处为s3stream)

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

更新2

此代码成功将缩略图文件上传到s3。但是我仍然很想知道如何将其流化。我认为这样会更有效率。

  #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)
Run Code Online (Sandbox Code Playgroud)

小智 -1

您研究过回形针宝石吗?gem 提供了与 s3 的直接兼容性并且运行良好。