Encode/DeCode Image to base64 in RhoMobile Apps

46 sec read

Encoding Image to base64 string
Rhodes comes with base64 library which helps to convert image to base64 string.
Lets see how.
Lets take an image from camera using RhoMobile library
[source language=”ruby”]
require ‘base64′
def take_photo
Camera::take_picture(“/app/Item/take_photo_callback”,{:format=>’JPG’})
end
[/source]
Now process the image taken via Smartphone camera to convert to base64
[source language=”ruby”]
def take_photo_callback
if @params[“status”]==”ok”
image_uri = @params[‘image_uri’]
base64_string = get_base64_image(image_uri)
#optionally write it to sd card or even send to server via restful service.
write_to_sdcard(base64_string)
end
end
[/source]
Now convert the Blob image into base64 format
[source language=”ruby”]
#method to encode image to base64 string
def get_base64_image(damaged_photo_record)
image_base64 = Base64.encode64(open(Rho::RhoApplication::get_blob_path(image_uri.strip)) { |io| io.read })
#replace new line and carriage return chars
filter_image = image_base64.gsub(/\r/,””).gsub(/\n/,””)
end
[/source]
Decoding base64 string to image and write it to SD card. For iPhone apps, you can display it directly on the view page
[source language=”ruby”]
def write_to_sdcard(base64_image)
File.open(“/sdcard/photo.jpg”, “wb”) do |file|
file.write(Base64.decode64(base64_image))
end
end
[/source]

Related posts:

My Testing Experience with Healthcare Project

Hi Folks, I am working on a healthcare related web application. I would like to share few interesting things that I came across while...
Ashwin Sundarabaskar
5 min read

Fix for Net::OpenTimeout: execution expired When on AWS with…

If you happen to see the error “Net::OpenTimeout: execution expired” and if it originating from /home/ubuntu/.rvm/rubies/ruby-x.x.x/lib/ruby/x.x.x/net/smtp.rb and if you are running your server on...
Praveen Kumar
15 sec read

One Reply to “Encode/DeCode Image to base64 in RhoMobile Apps”

  1. In Android version 2 it will be showing error as “Undefined method `unpack` for Nil class” for decode64() method ,It will be working fine in Android Version 4
    Any suggestion please share
    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *