Friday 19 October 2007

Converting binary data to image in HTML

Let's say you were making an Ajax request for an image, and the response is a base64 encoded string which you want to use to create an image in HTML. A way of doing so is to use "data:image/png;base64," at the start of your image source, and append the encoded string.

For example,

<img='data:image/<image format>;base64,<encoded string>' />

This will correctly render the encoded string into an image that can be displayed on the browser.

Using Gruff to create graphs, the Gruff::Base has a method called to_blob which draws the graph and returns the graph as a rendered binary. Simply return a base64 encoded version of it to the Ajax call to be processed.


# Controller
g = Gruff::Pie.new(300)
.
.
.

render :text => encode64(g.to_blob)

2 comments:

Unknown said...

Thanks! Helped me a lot. :D

MohNN said...

Hi,

PLease share working sample if possble as i am very new to HTML javascript.

Thanks,
Mohan