Zac Romero
Zac Romero

Reputation: 406

How do you display a png image in string format in Rails?

I have a function in Ruby that returns the data for a QR Code image in PNG format that works as follows:

puts generate_qr_code("this is a test")

�PNG

IHDk�XTPLTE,�)�[��tRNS@��f�IDATx���Kr��M�ѭ8)
                                                �<��q����(�x��H�$I�$I�$I�$I�$�+����

What would be the simplest way to take this string and display in a Rails view?

I have a couple of ideas on how this could be possilbe such as saving the data in a @img_data variable and the view some how displaying it. Or perhaps saving into a file and passing it's url. The images generated will only be used temporarily so saving the data somewhere wouldn't be necessary.

Upvotes: 3

Views: 2143

Answers (2)

Stefan
Stefan

Reputation: 114138

What would be the simplest way to take this string and display in a Rails view?

Construct a data URI using the Base64-encoded image data and pass it to the image_tag helper:

# controller
def show
  @image_data = generate_qr_code('this is a test')
end

# view
<%= image_tag "data:image/png;base64,#{Base64.strict_encode64(@image_data)}" %>

You could also wrap this in a helper method:

# helper
def qr_image_tag(text, options = {})
  image_data = generate_qr_code(text)
  data_uri   = "data:image/png;base64,#{Base64.strict_encode64(image_data)}"
  image_tag(data_uri, options)
end

# view
<%= qr_image_tag('this is a test') %>

Upvotes: 4

Martin Povolny
Martin Povolny

Reputation: 111

  def render_qr_code                                                               
    response.headers['Cache-Control'] = "public"                                                    
    response.headers['Content-Type'] = "image/png"                                 
    response.headers['Content-Disposition'] = "inline"                                              
    render :body => generate_qr_code("this is a test")                                                                 
  end    

Then in you view you do <img src="controller_name/render_qr_code">. You need a route etc...

Upvotes: 3

Related Questions