5

下面的代码调整了我的图像大小。但我不确定如何将其写入临时文件或 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"))

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

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

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

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

但是 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

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

我该如何更改我的代码

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)
4

2 回答 2

0

smallImage.to_blob?

以下来自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
于 2015-08-01T13:08:09.817 回答
-1

你看过回形针宝石吗?gem 提供与 s3 的直接兼容性并且效果很好。

于 2014-05-07T16:48:24.170 回答