开发者

How do you write an image at a url to your filesystem in Ruby?

开发者 https://www.devze.com 2023-03-16 10:32 出处:网络
If there is an image at a public url,开发者_高级运维 how would I write and save it to my local filesystem using Ruby?require \"open-uri\"

If there is an image at a public url,开发者_高级运维 how would I write and save it to my local filesystem using Ruby?


require "open-uri"

open("http://www.whatever.com/x.png") do |hnd|
  File.open("x.png","wb") {|file| file.puts hnd.read }
end

EDIT:

This allows you to use open to load a website, and treat it as normal file handle:

require "open-uri"

This loads your image, and passes a handle to the page body, as the parameter hnd:

open("http://www.whatever.com/x.png") do |hnd|

This opens a file in binary mode ( needed on Windows systems ), and writes the page's content into it:

File.open("x.png","wb") {|file| file.puts hnd.read }

The content is obtained via the read method, which tries to read it completely before writing it.

0

精彩评论

暂无评论...
验证码 换一张
取 消