Ruby file_get_contents equivalent - ruby-on-rails

I need to use this in my rails program so I can get the image contents and then base64 it. I know how to base64 it but I just don't know how I would get the image. Anyone know how?

Edited to retrieve from external URL:
PHP:
$image = file_get_contents("http://www.example.com/file.png");
Ruby:
require 'net/http'
image = Net::HTTP.get_response(URI.parse("http://www.example.com/file.png")).body

For http/https/ftp you can use OpenURI module:
require "open-uri"
image = open("http://www.example.com/file.png").read

Related

Ruby on Rails - External Image Url to Base64

is there anyway in Ruby on Rails to convert the image hosted in an image url (https://meo-fb-natal-dev.s3.amazonaws.com/participations/cropped/56658c5de2fc7116340000c0/635769180217506883-GD5A9264.jpg?1449495643) to Base64?
I've tried tons of things but none of them seem to work.
What exactly is not working?
Here is an example:
$> irb
>> require 'open-uri'
>> img = open("https://meo-fb-natal-dev.s3.amazonaws.com/participations/cropped/56658c5de2fc7116340000c0/635769180217506883-GD5A9264.jpg?1449495643")
# img variable is a tempfile with image
>> require 'base64'
>> Base64.encode64(img.read)
=> "/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJ\nChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/\n2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo\nKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAFTAoYDASIAAhEBAxEB/8QA\nHAAAAAcBAQAAAAAAAAAAAAAAAQIDBAUGBwAI/8QAShAAAgEDAgQEAwUGB..."
You can try this
url = "https://meo-fb-natal-dev.s3.amazonaws.com/participations/cropped/56658c5de2fc7116340000c0/635769180217506883-GD5A9264.jpg?1449495643"
ActiveSupport::Base64.encode64(open(url) { |io| io.read })

Read GB2312 encoding page using Ruby

I am trying to parse GB2312 encoded page (http://news.qq.com/a/20140824/015032.htm), and this is my code.
I am not yet into the parsing part, just in the open and read, and I got error.
This is my code:
require 'open-uri'
open("http://news.qq.com/a/20140824/015032.htm").read
And this is the error:
Encoding::InvalidByteSequenceError: "\x8B" on GB2312
I am using Ruby 2.0.0p247
Any solution?
I don't know exactly why this happens when calling .read, but you can work around it if you are using Nokogiri. Just pass the file object directly to Nokogiri without calling .read:
require 'open-uri'
file = open("http://news.qq.com/a/20140824/015032.htm")
document = Nokogiri(file)
I cannot duplicate the error using 2.0.0p247,
require 'open-uri'
open("http://news.qq.com/a/20140824/015032.htm").read
Works fine.
However
require 'open-uri'
open("http://news.qq.com/a/20140824/015032.htm").read.encode('utf-8')
will raise the error
Encoding::InvalidByteSequenceError: "\x8B" on GB2312
Are you trying to do some encoding conversion?
you can try this
document = Nokogiri::HTML(open("http://news.qq.com/a/20140824/015032.htm"), nil, "GB18030")

Convert picture to binary BASE64

How do I convert a picture to binary BASE64 and send it by post to another API to be saved?
It looks something like:
User imports a photo through the HTML form and it transforms it to binary BASE64 code:
base64_encode = Base64.encode64(img_from_fild_form)
The data is sent to another API (media):
options = { :auth_key=>01qw6, :post_id=>20, :base64_encode=>base64_encode }
HTTParty.post('localhost:9000/save_image', options)
if the input is from a rails form then it probably as easy as:
Base64.encode64(params[:key_for_file].read)
the uploaded file is likely an instance of ActionDispatch::Http::UploadedFile
It should be as easy as:
require 'base64'
base64_encoded = Base64.encode64(img_from_file_form)
Hope that helps. :)

How will I save data from javascript's canvas.toDataURL to an image file in ruby?

How will I save data from javascript's canvas.toDataURL to an image file in ruby?
The sample code below create the image but gives an error saying the format is not recognized or damaged
require 'base64'
chart1 = params[:chart1].split(',')
image = Base64.decode64(chart1[1])
File.open("#{Rails.root}/test.png", 'wb') do|f|
f.write(image)
end
Thanks!
NOTE: Edited. This is now ok and working
Copying the answer from the comments in order to remove this question from the "Unanswered" filter:
p0rter noticed:
why do you have to call Base64.decode64 twice?
steamboy acknowledged:
#p0rter nice catch. its now working. tnx

RMagick can not read remote image

My env is Linux centos, and use ruby 1.8.7, and the code is here below:
require 'rubygems'
require 'RMagick'
Magick::Image.read("http://image.domain.com/image.darenhui.com/images/random_bg/01.jpg")[0]
it throws error like below:
in `read': no decode delegate for this image format `//image.domain.com/images/random_bg/01.jpg' # error/constitute.c/ReadImage/532 (Magick::ImageMagickError),
but if i read from local like:
require 'rubygems'
require 'RMagick'
Magick::Image.read("/local/staticimages/random_bg/01.jpg")[0]
everything is ok.
I run identify -list format and see below:
JPEG* JPEG rw- Joint Photographic Experts Group JFIF format (62)
JPG* JPEG rw- Joint Photographic Experts Group JFIF format (62)
but when i test by identity for "http://image.domain.com/image.darenhui.com/images/random_bg/01.jpg" to fail, but success for "/local/staticimages/random_bg/01.jpg"
Can someone give me some clue? thank you in advance.
Magick::Image.read does not support URL links. But you can read the remote image using ruby open method:
require 'rubygems'
require 'RMagick'
require "open-uri"
image = Magick::ImageList.new
urlimage = open("http://www.jewelinfo4u.com/images/Gallery/ruby.jpg") # Image Remote URL
image.from_blob(urlimage.read)
# crop = image.crop(10,10,200,300) You can crop this image too
# crop.write('C:/nameofyourNewImage.jpg') If you want to save the image you can use this line in windows
Fast forward to May 2014, and I'm able to just...
require 'rubygems'
require 'RMagick'
include Magick
image = ImageList.new("http://www.jewelinfo4u.com/images/Gallery/ruby.jpg")
And it just works. Feels good.
(Tested on ImageMagick 6.8.8-9 Q16)
EDIT: Does not seem work on Heroku Cedar stack (ImageMagick 6.5.7-8 2012-08-17 Q16) though. :/
As far as I can see Magick::Image.read does NOT support URLs, only files/file handles - see http://www.imagemagick.org/RMagick/doc/image1.html#read where it says that it
Reads all the images from the specified file.
It is implemented by the C function ReadImage which does not support URLs - see the ImageMagick source at line 394 here.
IF you want to open an image from a URL you need to download the image somehow - to a file or a stream... then you can feed that file or stream to Magick...
You can read a file from a url with open-uri, then feed that into Rmagick's Image::from_blob.
Example:
require 'open-uri'
require 'rubygems'
require 'Rmagick'
image_url = 'http://example.com/image.jpg'
image = Magick::Image.from_blob(open(image_url).read).first
Note that you should additionally take care to handle exceptions arising from the open HTTP request. Ie, what happens if you get a 404, or a non-image response?
As of rmagick (4.1.2), Image.read does support URL links. In my case, I was reading an image, specifically a png file from AWS S3. This was via localhost. Updating to the latest version should fix this problem.

Resources