0

I'm trying to display an image from byte array using Angularjs. I have tried each of the solutions I've found on the web, but none of them are working.

Currently, in my HTML, I have:

        <img ng-src="data:image/jpeg;base64,{{company.imgCompanyLogo}}" />

My controller code is:

angular.module('myModule').controller('ContractorCtrl', function ($scope, contractorService, $interval, $window) {

    getcontractorInfo();
    function getcontractorInfo() {
        contractorService.getContractorInfo()
        .success(function (data) {
            $scope.company = data;
        });
    };

Everything I've read says what I am doing should work. All the data retrieved displays except for the picture, and I'm sure the name of the field "imgCompanyLogo" is correct. What am I missing?

Any assistance is greatly appreciated!

Rani Radcliff
  • 4,856
  • 5
  • 33
  • 60
  • can you do a `console.log(data.imgCompanyLogo)` to verify? Also, going off your title, `company.imgCompanyLogo` should be a base64 string, not a byte array. – Ronnie Sep 28 '15 at 16:44
  • It gives me a Failed:data:image/jpeg;base64,[255,216,255,224,0,16,74,70,73,70,0,1,1,1,0,31,0,31,…,40,162,138,0,40,162,138,0,40,162,138,0,40,162,138,0,40,162,138,0,255,217] Failed to load resource: net::ERR_INVALID_URL – Rani Radcliff Sep 28 '15 at 16:47
  • 1
    That's not base64 data. –  Sep 28 '15 at 16:49
  • from what I understand it is a "byte" array. Any ideas? – Rani Radcliff Sep 28 '15 at 16:52
  • you need to convert your byte array to a base64 string – Ronnie Sep 28 '15 at 16:53

2 Answers2

0

You need to convert the array to a base64-encoded string. This question has information on converting it: ArrayBuffer to base64 encoded string.

With mobz answer, you can add the function into the scope:

$scope.arrayBufferToBase64 = function( buffer ) {
    var binary = '';
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
    }
    return window.btoa( binary );
}

From there, you can just do:

<img ng-src="data:image/jpeg;base64,{{arrayBufferToBase64(company.imgCompanyLogo)}}" />

It'll probably be pretty slow FYI. If you can, you might be able to leverage canvas to improve performance.

Community
  • 1
  • 1
0

Make it a filter so that you can use it simple Like

app.filter('bytetobase', function () {
    return function (buffer) {
        var binary = '';
        var bytes = new Uint8Array(buffer);
        var len = bytes.byteLength;
        for (var i = 0; i < len; i++) {
            binary += String.fromCharCode(bytes[i]);
        }
        return window.btoa(binary);
    };
});

And just call the filter in you img tag as

<img ng-src="data:image/JPEG;base64,{{picture | bytetobase}}" alt="..." width="100" height="100">
Nair Athul
  • 823
  • 9
  • 21