Ruby on Rails - External Image Url to Base64 - ruby-on-rails

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

Related

Convert pdf file to base64 string

I have working Paperclip gem in my app for documents (pdf, doc). I need to pass the document to some other third party application via post request.
I tried to convert the paperclip attachment via Base64 but it throws error:
no implicit conversion of Tempfile into String
Here is how I did it:
# get url from the paperclip file
url = document.doc.url # https://s3-ap-southeast-1.amazonaws.com/xx-eng/documents/xx/000/000/xx/original/doc.pdf
file_data = open(url)
# Encode the bytes to base64 - this line throw error
base_64_file = Base64.encode64(file_data)
Do you have any suggestion how to avoid the Tempfile error?
You need to read file first.
base_64_file = Base64.encode64(file_data.read)
Here is working example:
$ bundle exec rails c
=> file = open("tmp/file.pdf")
#> #<File:tmp/receipts.pdf>
=> base_64 = Base64.encode64(file)
#> TypeError: no implicit conversion of File into String
=> base_64 = Base64.encode64(file.read)
#> "JVBERi0xLjQKMSAwIG9iago8PAovVGl0b/BBQEPgQ ......J0ZgozMDM0OQolJUVPRgo=\n"
The answer from #3елёный didn't work to me - maybe because it's the S3 file.
However I managed to find a way with Paperclip method:
file_data = Paperclip.io_adapters.for(url).read
base_64_file = Base64.encode64(file_data)

How can I download an image from a website using Rails?

I'm using Selenium-Webdriver, OpenUri and Nokogiri to scrape a website. I want to download a particular image from said website to my Ubuntu computer. I tried a few different methods but each of them gives a different error message.
Here's my base code, which opens the website and gets the image url (everything after this I ran in my pry console):
require 'open-url'
require 'selenium-webdriver'
require 'nokogiri'
require 'uri'
url = "https://www.google.com/"
browser = Selenium::WebDriver.for :chrome
document = open(url).read
parsed_content = Nokogiri::HTML(content)
image = "https://www.google.com" + parsed_content.css('#hplogo').attr('src').value
binding.pry
1) Here's the first thing I tried to download the image:
download = open(image)
IO.copy_stream(download, '~/image.png')
For this, I got the following error:
Errno::ENOENT: No such file or directory # rb_sysopen - ~/image.png from (pry):44:in 'initialize'
As per this question, I tried adding a directory in the code:
FileUtils.mkdir_p(image) unless File.exist?(image)
But I got the same error.
2) Next I tried this:
open('image.png', 'wb') do |file|
file << open(image).read
end
and this returns
#<File:image.png (closed)
but the file isn't anywhere on my computer and I can't figure out what that message means.
3) Next I tried
IO.copy_stream(open(image), 'image.png')
which simply returned this:
5482
but again, I have no idea what that means and the file isn't anywhere.
4) Finally I tried
read_image = open(image).read
File.open(image, 'image.png') do |file|
file.puts read_image
end
which outputs
ArgumentError: invalid access mode image.png
from (pry):53:in 'initialize
What am I doing wrong? Was I close with any of my approaches?
File open second argument is mode for file openning.
read_image = open(image).read
File.open('image.png', 'w+') do |file|
file.write read_image
end
Your third variant works good.
5482 - length of file. File 'image.png' in same directory as your .rb file.

Read a file from github

I want to read a file from github repository in my ruby script. Say I want to read Gemfile from my repo on github, URL for which would be like: "http://www.github.com/myrepo/blob/master/Gemfile".
I tried using File.readLink("http://www.github.com/myrepo/blob/master/Gemfile") but this gives me error saying "'readlink': No such file or directory # rb_readlink".
How do I read a file using the github URL?
You should try to fetch raw content from github files like:
require 'net/http'
uri = "https://raw.githubusercontent.com/username/myrepo/master/Gemfile"
uri = URI(uri)
file = Net::HTTP.get(uri)
With the below code, I was able to read the content of the file.
require 'open-uri'
raw_url = "https://raw.githubusercontent.com/username/myrepo/master/Gemfile"
open(raw_url) {|f|
f.each_line {|line| p line}
}

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.

Ruby file_get_contents equivalent

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

Resources