Attachment_fu image saving from Base64 string.

Posted by Bhushan G Ahire | Posted in iphone, JRuby, Rails, ruby | Posted on 04-01-2011

0

Just the other day, I was struggling with the problem that I needed to create an attachment from a base64 encoded image passed by a Flash object. My first idea was to encapsulate the data in an UploadedFile object, but I couldn’t get it to work without writing some pretty ugly code. I could also use the LocalFile model as described here, which you can use to pass a local file to attachment_fu. I figured that wouldn’t do the job properly either; you would write the data to the filesystem, pass the file, and attachment_fu would load it again.

Looking in the attachment_fu code, I found that it expects either a File or a StringIO. Moreover, it expects that it contains a original_filename method and a content_type method. My solution was therefore to create a small wrapper for the imagedata, which is based on StringIO:

# Usage example:
#
# model = Model.new()
# model.uploaded_data = VirtualImage.new(image_data, filename, mime_type)
# model.save
class VirtualImage < StringIO
 # Image mime types
 MIME_TYPES = [ "image/gif", "image/ief", "image/jpeg", "image/jpeg", "image/jpeg", "image/x-portable-bitmap", "image/x-portable-graymap", "image/png", "image/x-portable-anymap", "image/x-portable-pixmap", "image/cmu-raster", "image/x-rgb", "image/tiff", "image/tiff", "image/x-xbitmap", "image/x-xpixmap", "image/x-xwindowdump" ]

 # The filename of the image to be stored
 attr_reader : original_filename
 # The content type of the image_data
 attr_reader :content_type

 def initialize(image_data, filename, mime_type)
  raise "Unrecognized MIME type '#{mime_type}'" if !MIME_TYPES.include?(mime_type)
  @content_type = mime_type
  @original_filename = filename
  super(image_data)
 end

end