路径名称包含图片网址的空字节(存在时)

时间:2019-05-31 09:58:02

标签: ruby-on-rails ruby-on-rails-4 open-uri

我正在使用以下代码通过Dimensions Gem获取图像的宽度。

file_path = "http://localhost:3000/uploads/resize/avatar/25/ch05.jpg"
width = Dimensions.width(open(file_path).read)

当我将图像url放在url bar中时,它将在浏览器中呈现该图像。我想做的是获取图像的宽度。谁能知道我在做什么错?

1 个答案:

答案 0 :(得分:0)

因此,您的问题是Dimensions需要一个文件路径来确定图像的宽度。使用openStringIO将返回open(...).read,而String将返回File.open

Dimensions#width

def width(path)
  io_for(path).width
end

Dimensions#io_for

def io_for(path)
  Dimensions(File.open(path, "rb")).tap do |io|
    io.read
    io.close
  end
end

要解决此问题,您可以将图像下载到Tempfile,然后使用该路径传递给Dimensions.width

 path = "http://localhost:3000/uploads/resize/avatar/25/ch05.jpg"
 t = Tempfile.new                 # you could add a name but it doesn't matter
 t.write(open(path).read)         # write the image to the Tempfile
 t.close                          # must close the file before reading it
 width = Dimensions.width(t.path) # pass the Tempfile path to Dimensions
 t.unlink                         # deletes the Tempfile 

我们可以使它看起来更简洁一些:

def get_width_of_url_image(url)
  t = Tempfile.new.tap do |f| 
    f.write(open(url).read)
    f.close
  end
  width = Dimensions.width(t.path)
  t.unlink and width
end

get_width_of_url_image("https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png")
#=> 272