Reputation: 28783
We're using a Rest endpoint that returns an actual image like so:
@image = RestClient.get('http://example.com/api/v1/scopes/12345/icon', headers).body
And the response is something like:
�PNG
���
IHDR���������H�۱���PLTE������� ��/��>��M��\��j��y������������������������������������������5��J��c�����������������3��i��������������:��Z��z�����������C��e��������������.��V��~���������(��U����������@��r�����K��|����������
��B��w���������+��f����*����E��������O������������T�������<����������F����������b��1�܀�����0����?�� �֟��N��S���������L�������������W��������m������s��������;��l��k��%�ڑ�����o��n����4��������`�����_�����؊���ْ�����$�����"�ڜ�������ց��d��������������!�ڥ��g�����������x��I�����և����X���ن�����H��,�ۿ����������p��)�����#��������D��}����h��8�ݝ��������2�ܳ��[������'��t��9��q��a������]��������6��������{�����������������
��u����-��7��P�����A��^����������������������R����=��Y��Q��&�ڼ�����G��v���بxi���=�IDATx���a�����ݳm�����3�L
We want to Base64 encode this and display it on a View in our Rails app:
<%= image_tag(Base64.encode(@image)) %>
However it seems that the Base64 is expecting us to Open a file and pass that... e.g.
<%= image_tag(Base64.encode(File.open(@image).read)) %>
But this API returns the actual image...
Tried using send_data
as well...
Base64.encode64(send_data(RestClient.get('http://example.com/api/v1/scopes/12345/icon', headers).body, disposition: 'inline'))
But then just sends the image to the browser and bypasses our view...
How can we Base64 encode and display this image on our View?
Upvotes: 2
Views: 1851
Reputation: 21110
Converting the binary data to base64 and passing that as data source isn't enough on its own. This would produce:
<img src="asdf...sdf==" />
Which isn't a valid source.
You have to create an data URI:
<%= image_tag("data:image/png;base64,#{Base64.encode64(@image)}") %>
This assumes your data has a MIME type of image/png
. You could make this dynamic, but you have to extract the MIME type from the file or the extension somehow.
You might also be able to leave out the MIME type, since it's optional for data URIs. I'm not sure how the webbrowser would react to this though:
<%= image_tag("data:;base64,#{Base64.encode64(@image)}") %>
You could also create a helper for this. The asset pipeline already has a helper asset_data_uri
. However since you fetch your images dynamically they are not part of the static server assets you might not be able to use it.
Upvotes: 4