Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write StringIO to Tempfile

Tags:

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

like image 635
Haris Krajina Avatar asked Aug 13 '13 18:08

Haris Krajina


2 Answers

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).

like image 69
Dylan Markow Avatar answered Oct 03 '22 11:10

Dylan Markow


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.

like image 43
itayad Avatar answered Oct 03 '22 10:10

itayad