Sending images with your Ruby / Rails API - Receive them in RubyMotion

Base64 encoding to translate images to binaries and back.

Posted on May 24, 2015

Rails Side

For an iOS game I’ll eventually release, I store images for each “story” on a Story model. image_file is one of the attributes and it’s just a string of the image’s file name. There’s a before_save callback that stores a Base64 binary version of the image on that model’s instance.

before_save :generate_image_binaries

...

file_path = "#{Rails.root}/app/assets/images/#{image_file}"
file = File.read(file_path)
self.image = Base64.encode64(file).gsub(/\n/, "")

RubyMotion Side

After receiving a “Story” object in RubyMotion through an API call, I initialize an NSData object with the Base64 encoded image. These are stored with NSDefaults. I’m using a globally variable here. Usually recommended blah blah blah.

$defaults["image-0"] = NSData.alloc.initWithBase64EncodedString(story[:image], options: 1)

This app uses RubyMotion Query (RMQ). This is an awesome library. Recently, RMQ and ProMotion(and more) combined as RedPotion. Haven’t tried that yet, but I’m excited to. Anyway, later when showing Story views, I set the image in RMQ. It shouldn’t be too hard to adapt the code below if you aren’t using RMQ. The part that matters is UIImage.imageWithData.

def story_image(st)
  st.image = UIImage.imageWithData($defaults['image-0'])
  ratio = st.image.size.width / st.image.size.height
  st.view.contentMode = UIViewContentModeScaleAspectFit
  st.frame = {t: 0, l: 0, w: app_width, h: app_width/ratio}
  st.background_color = UIColor.blackColor
end

Comments