Richard
Richard

Reputation: 8935

Display Database Image in Javascript

I am using Ionic 2 calling a RESTful Service (JSON) in Java and a MySQL database. I am trying to display an image that is stored in the database, and render it in ionic.

Everything works perfectly, except I am struggling to get an image to display.

I have a PNG image stored in MySQL (type LONGBLOB). Then I access it, and in Java, convert it to Base64.

import org.apache.commons.codec.binary.Base64;
subCategory.setIcon(Base64.encodeBase64(subCategory.getIcon()));

JSON:

"icon" : "Vm0wd2QyUXlVWGxWV0d4V1YwZDRWMVl3Wk...lpRVVQwOQ=="

Then once received via JSON, I display it in html:

<img src="data:image/png;base64,{{item.icon}}" />

It just displays the image placeholder with no image.

I have also tried to decode the image with this Javascript:

icon = atob(icon);

and

 b64DecodeUnicode(str) {
    return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
}

with no success.

Upvotes: 1

Views: 629

Answers (1)

Richard
Richard

Reputation: 8935

This works:

<img src="data:image/png;base64,{{item.icon64}}" />

and

  b64DecodeUnicode(str) {
    return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
}

Upvotes: 1

Related Questions