0

我试过(取得了一些成功)

require 'open-uri'
require 'chunky_png'

image_url = "http://res.cloudinary.com/houlihan-lokey/image/upload/c_limit,h_75,w_120/ixl7z4c1czlvrqnbt0mm.png"
# image_url = "http://res.cloudinary.com/houlihan-lokey/image/upload/c_limit,h_75,w_120/zqw2pgczdzbtyj3aib2o.png" # this works

image_file = open(image_url)
image = ChunkyPNG::Image.from_file(image_file)
puts image.width

有些图像有效,有些则无效。错误:

TypeError: no implicit conversion of StringIO into String
from /Users/theuser/.rvm/gems/ruby-2.0.0-p247/gems/chunky_png-1.3.3/lib/chunky_png/datastream.rb:66:in `initialize'
from /Users/theuser/.rvm/gems/ruby-2.0.0-p247/gems/chunky_png-1.3.3/lib/chunky_png/datastream.rb:66:in `open'
from /Users/theuser/.rvm/gems/ruby-2.0.0-p247/gems/chunky_png-1.3.3/lib/chunky_png/datastream.rb:66:in `from_file'
from /Users/theuser/.rvm/gems/ruby-2.0.0-p247/gems/chunky_png-1.3.3/lib/chunky_png/canvas/png_decoding.rb:53:in `from_file'
from (irb):5
from /Users/theuser/.rvm/rubies/ruby-2.0.0-p247/bin/irb:16:in `<main>'

我将在 Heroku 上运行它,我想知道——有没有一种可靠的方法可以在不创建临时文件的情况下实现这一点?

4

1 回答 1

1

问题在于文件太小而无法open为其创建临时文件。

解决方案是不依赖临时文件,而是将图像读入内存并使用 ChunkyPNG 的 Image.from_blob:

require 'open-uri'
require 'chunky_png'

image_url = "http://res.cloudinary.com/houlihan-lokey/image/upload/c_limit,h_75,w_120/ixl7z4c1czlvrqnbt0mm.png"

image_file = open(image_url).read
image = ChunkyPNG::Image.from_blob(image_file)
puts image.width

这可能不适用于大图像,但适用于我的应用程序。

于 2014-11-19T18:14:48.883 回答