Josh
Josh

Reputation: 21

Image from URL Code Ruby

I'm making a random cat picture cracker, and decided that Ruby was the best. This code,

require 'chunky_png'
require 'open-uri'

d=rand(2000)+1

url="http://www.placekitten.com/"
open('image.png', 'wb') do |file|
  file << open(url,d).read
end

This is probably a really easy fix, but I'm new to ruby.... I get this error when I run it

C:/Ruby200/lib/ruby/2.0.0/open-uri.rb:146:in open_uri': invalid access mode 200 (URI::HTTP resource is read only.) (ArgumentError) from C:/Ruby200/lib/ruby/2.0.0/open-uri.rb:688:inopen' from C:/Ruby200/lib/ruby/2.0.0/open-uri.rb:34:in open' from Kittens.rb:8:inblock in ' from C:/Ruby200/lib/ruby/2.0.0/open-uri.rb:36:in open' from C:/Ruby200/lib/ruby/2.0.0/open-uri.rb:36:inopen' from Kittens.rb:7:in `'

Upvotes: 0

Views: 1830

Answers (1)

Arie Xiao
Arie Xiao

Reputation: 14082

If you want to get images from http://www.placekitten.com/, you should append width (if height is ignored, it is set to width as default) to the URL. However, in your code, you have put the random width at the position of the second parameter of open, which is intended to be the open mode (r, w, a, etc). That's why Ruby complains about "invalid access mode XXX", where XXX is the random code d you get at that time the script is executed.

require 'chunky_png'
require 'open-uri'

d=rand(2000)+1

url="http://www.placekitten.com/"
open('image.png', 'wb') do |file|
  file << open(url + d.to_s).read
end

BTW, it's a good site for Web UI designer :-)

Upvotes: 1

Related Questions