Transcode Byte Array into Base64 String Using AngularJS

I am receiving a byte array in the service response, and I need to display that image in an image field on my HTML page. Can anyone provide guidance on how to implement this? I have searched for solutions on Stack Overflow but have not found a valid solution yet. Here is my code snippet:

this.getPrescription = function(pres_id) {
     var deff = $q.defer();
     $http({
           method: "GET",
           url: "www.abc.com/api/&prescriptionOnly=false&page=1",
           headers: {
           'Authorization': 'Bearer ' + localStorage.getItem("chemist_access_token"),
           'Content-Type': 'application/json'
           },
           responseType: 'arraybuffer'
           }).then(function(objS) {
                   console.log("getPrescription:\n" + JSON.stringify(objS))
                   deff.resolve(objS);
                   }, function(objE) {
                   errorHandler.serverErrorhandler(objE);
                   deff.reject(objE);
                   });
     return deff.promise;
     };

In my controller, I am calling it like this:

$scope.getPrescription = function(id) {
    $ionicLoading.show({
        template: '<ion-spinner icon="spiral"></ion-spinner>',
        noBackdrop: false
    });
    serverRepo.prescriptionGet(id).then(function(objS) {
        console.log("orderByCustomer:\n" + JSON.stringify(objS));
        $scope.picdata=$window.URL.createObjectURL(new Blob([objS.data], {type: 'image/png'}));

        $ionicLoading.hide();
        console.log("getOrderByNew_success_loadMore:\n" +$scope.picdata);
    }, function(objE) {
        $ionicLoading.hide();
    });
}

Upon checking my console, it displays the following message: getOrderByNew_success_loadMore: blob:file:///0aa86d9f-61a1-4049-b18c-7bf81e05909f

Answer №1

Convert a byte array to base64 with this handy filter:

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);
    };
});

To display the converted image, use:

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

If you need to save the base64 string in a variable, do this:

var image = $filter('bytetobase')($scope.picture );

Answer №2

If you ever find yourself in need of displaying an image from a byte array, one way to do so is by creating an object using Blob and obtaining its URL to pass into the image tag source. It's important to set the correct type during blob creation by specifying the type in the last parameter of the Blob constructor.

$http.get(url, {responseType: 'arraybuffer'})
  .then(function(response) {
    return $window.URL.createObjectURL(new Blob([response.data], {type: 'image/png'}));
  });

Once you no longer require working with your object (e.g. after the image has loaded in the appropriate img tag), you can update it as needed.

Update

An alternative solution involving base64

$scope.getPrescription = function(id) {
  $ionicLoading.show({
    template: '<ion-spinner icon="spiral"></ion-spinner>',
    noBackdrop: false
  });
  serverRepo.prescriptionGet(id).then(function(objS) {
    console.log("orderByCustomer:\n" + JSON.stringify(objS));
    // Creating file reader
    var reader = new window.FileReader();
    // Creating blob from server's data
    var data = new Blob([objS.data], {type: 'image/jpeg'});
    // Start reading data
    reader.readAsDataURL(data); 
    // Once all data is read
    reader.onloadend = function() {
      // Set image source
      $scope.picdata = reader.result;
      // Trigger digest loop
      $scope.$apply();
    }

    $ionicLoading.hide();
    console.log("getOrderByNew_success_loadMore:\n" +$scope.picdata);
    }, function(objE) {
    $ionicLoading.hide();
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Angular with a hapi.js server that supports JSONP data requests

In my project, there is an endpoint specifically set at /api/profile that accepts post parameters. var http = require('http'); var serverConfig = require('../server.config.js'); var request = require('request'); module.expo ...

express-session is failing to maintain persistence and refusing to transmit a cookie to the browser

I am currently developing a web application using the MERN stack (React, Node.js, Express, and MongoDB). I have integrated express-session in my Node.js project, but for some reason, I cannot see the connect.sid cookie in the browser. Additionally, it appe ...

Creating a script that automatically launches the terminal and executes specific commands

Can anyone help me with creating a file that, when clicked on, opens a command prompt and executes the following commands? cd desktop\discordBOT node . Many thanks in advance! ...

Using jQuery to retrieve a file that has been uploaded through an input field with the type of 'file'

I am looking to extract the file that has been uploaded using an <input type='file'> tag. Currently, when I use $('#inputId').val(), it only retrieves the name of the file, not the actual content of the file itself. I came acros ...

How do I extract a specific property from an array of objects and assign it to a new array in Typescript 2?

I've got this TypeScript 2 "model" that looks like this: export class MyModel { myProperty1: string; myProperty2: string; ... } In addition to the model, I have another class defined as follows: // Imports excluded for brevity @Component . ...

Creating a custom service that utilizes $cacheFactory

Utilizing $cacheFactory to store configurations and user data for one-time retrieval: var cache = $cacheFactory("Temp"); var getCachedData = function (url) { var data = cache.get(url); var deferred = $q.defer(); if (data) { ...

Monitor the true/false status of each element within an array and update their styles accordingly when they are considered active

Currently, I am attempting to modify the active style of an element within an array. As illustrated in the image below - once a day is selected, the styles are adjusted to include a border around it. https://i.stack.imgur.com/WpxuZ.png However, my challe ...

Is there a way for me to showcase the most recently added item above the existing one?

Is there a way to show the most recently added item at the top of the list instead of at the bottom? <div className="App"> <h2>{this.state.title}</h2> <form ref="myForm" className="myForm"> <input type="tex ...

Incorporating <span> elements into a comma-separated list using Jquery on every other item

When I receive a comma-separated list of items from a database and insert them into a table cell, I want to apply alternating styles to make it easier for users to distinguish between them. For example: foo, bar, mon, key, base, ball I'm looking to ...

Leverage the power of npm to utilize various javascript libraries for

I seem to be a bit confused here. Currently, I have the following code snippets: import * as angular from 'angular'; import 'ts-angular-jsonapi'; Interestingly, no errors are being returned with this setup. But as soon as I try this: ...

Select a Date: Input for Date Selection

Is it possible to restrict the selection of certain days using HTML date input validation? Some booking websites have a feature where an interactive calendar only allows users to select specific dates for events, while others are greyed out and cannot be c ...

Incorporating External JavaScript and CSS specifically for a single component

In my Angular 4 application, I have a specific component that requires the use of a js and css file. While most guidelines suggest placing these files in the Index.html file, I prefer to only load them when this particular component is accessed, not on e ...

Having difficulty resolving all parameters for the component: (?, [object Object]) in the Jasmine component Unit Test

While defining a UT for a component with an extended class using i8nService and ChangeDetectionRef, I encountered an error preventing me from instantiating it: Failed: Can't resolve all parameters for BrandingMultiselectComponent: (?, [object Object] ...

Using the ui-router to repeatedly call an AngualrJS directive

I've encountered an issue with my HTML audio player in AngularJS. When the page is refreshed, everything works perfectly - I can set the source and play audio without any problems. However, if I navigate to another state in the app and then try to loa ...

Conditional rendering with React.js in the DOM

Just starting out with React and encountering an issue with rendering using reactDom: index.js import ReactDOM from 'react-dom'; import A from 'components/A'; import B from 'components/B'; render(<A />, document.getEl ...

Utilizing AngularJS to achieve similar functionality to window.bind()

When trying to set the context of a function and pass it as a callback, I am following this approach: myController.myService.validateToken(param) .then( myController.myService.getToken.bind( myController.myService ) ); myController.myService.getToken ...

Can I retrieve the element of any DOM element I'm currently hovering over using JavaScript?

Suppose I have this HTML snippet: <body> <div id="1"> <span class="title">I'm a title!</span> </div> <div id="2">I'm the first element!</div> <div ...

Error: Unable to convert undefined or null values to an object - encountered while attempting to run a MySQL query within the router

I have a situation where I am running multiple MySQL queries in a route. The final query is a SELECT statement using the 'email' value retrieved from a previous query as a condition. When testing these 'email' values in MySQL Workbench, ...

Hold on for the completion of Angular's DOM update

I am facing an issue where I need to connect the bootstrap datepicker to an input field generated by AngularJS. The typical approach of using jQuery to attach the datepicker doesn't work as expected because the element is not yet available: $(functi ...

When utilizing the `useLocation` hook, the location information appears to be missing

When utilizing a HashRouter, and inside a component making use of useLocation, there seems to be an inconsistency between the window.location object and the location object retrieved from useLocation. While writing this, I have observed that there might b ...