Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I download a picture using Ruby?

Tags:

http

ruby

I want to download this picture using Ruby. How do I do that?

http://farm1.static.flickr.com/92/218926700_ecedc5fef7_o.jpg 

I am using Mac OS.

like image 980
Roger Avatar asked Jul 02 '09 13:07

Roger


People also ask

How to download a file in Ruby?

Plain old Ruby The most popular way to download a file without any dependencies is to use the standard library open-uri . open-uri extends Kernel#open so that it can open URIs as if they were files. We can use this to download an image and then save it as a file.

How do I read an image in Ruby?

You need to invoke mspaint.exe with the applicable command line flags. Do note though that I don't believe MSPaint handles JPG files. You'd need to search around google or perhaps submit another question regarding MSPaint and opening files via the command line.

How do I download a file in rails?

For Example: i Have my file in SVG folder inside Public Directory. Now we Can Access any file in Public Folder Like below and Pass id and Download option. Download option rename any file which u want to download. Now Click able link is Ready We Can Click on Above link to Download the File.

What is a Ruby file?

Ruby is a powerful scripting language. Scripts can be used to automate tasks such as creating and searching files and managing and organizing subdirectories. Companies like GitHub, Chef and Puppet use Ruby for scripting.


2 Answers

 require "open-uri"  open("your-url") {|f|    File.open("whatever_file.jpg","wb") do |file|      file.puts f.read    end }   
like image 81
Geo Avatar answered Sep 28 '22 21:09

Geo


Try using the Mechanize gem:

Start with: gem install mechanize to install Mechanize.

Then:

require 'rubygems' require 'mechanize'  agent = Mechanize.new link = 'http://www.asite.com/pic.jpg' agent.get(link).save "images/pic.jpg"  

EDIT: To make things cleaner I would suggest you use the File's name itself when you save the image. I had an issue saving bulk images because they were not formated correctly. The images were saved like this:

#pic.jpg(1) #pic.jpg(2) #etc. 

Thats why you should probably use the image name as the file name like this:

agent.get(src).save "images/#{File.basename(url)}" 

File.basename takes the image url and just returns the the actual image name:

File.basename("http://www.asite.com/pic.jpg") # returns the image name pic.jpg 
like image 31
Stefan Ciprian Hotoleanu Avatar answered Sep 28 '22 19:09

Stefan Ciprian Hotoleanu