Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrieve filename and content-type from base64 encoded image ruby on rails

I am trying to retrieve the content-type and filename of an image which i am receiving in base64 encoded format.

here is the code which is doing a POST request with the base64 encoded image

require 'net/http'
require "rubygems"
require 'active_support'

url = URI.parse('http://localhost:3000/')
image = ActiveSupport::Base64.encode64(open("public/images/rails.png").to_a.join)
post_params = {'image' => image }
Net::HTTP.post_form(url, post_params)

In the controller, I need to get the content-type and filename of this image. So first I am decoding it

image = ActiveSupport::Base64.decode64(params[:image])
image_data = StringIO.new(image)

and then I am stuck!

I basically want to save this image using paperclip. Need some serious help!

UPDATE : I can't send params for content-type and filename. I was just mimicking the client which is sending this (and i have no control on adding extra params)

like image 580
Madhusudhan Avatar asked Aug 05 '11 12:08

Madhusudhan


1 Answers

You could decode the raw bytes using one of the various ImageMagick libraries and then ask ImageMagick for the format. For example, with RMagick:

require 'rmagick'
bytes = ActiveSupport::Base64.decode64(params[:image])
img   = Magick::Image.from_blob(bytes).first
fmt   = img.format

That will give you 'PNG', 'JPEG', etc. in fmt. ImageMagick checks the bytes for magic numbers and other identifying information so it doesn't need a filename to know what sort of image you're giving it.

As far as the filename goes, you're out of luck unless someone explicitly tells you what it is. The filename rarely matters anyway and you should never use a filename you didn't generate for saving anything; a user supplied filename should only be used to display the name to people, make up your own filename (that you know is safe) if you need one.

like image 115
mu is too short Avatar answered Sep 28 '22 02:09

mu is too short