I am trying in ruby to read image from url and than save it to Tempfile
to be later processed.
require 'open-uri' url = 'http://upload.wikimedia.org/wikipedia/commons/8/89/Robie_House.jpg' file = Tempfile.new(['temp','.jpg']) stringIo = open(url) # this is part I am confused about how to save StringIO to temp file? file.write stringIo
This does not work that is resulting temp.jpg
is not valid image. Not sure how to proceed with this.
Thanks
You're super close:
file.binmode file.write stringIo.read
open(url)
is just opening the stream for reading. It doesn't actually read the data until you call .read
on it (which you can then pass in to file.write
).
You could also create your tempfile with the correct encoding, like so:
file = Tempfile.new(['temp','.jpg'], :encoding => 'ascii-8bit')
This is the same as setting the file to binmode.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With