Error Message: Unable to Load User Profile Pictures from Microsoft Graph

Currently, I am developing an application that makes requests for user profile photos from Microsoft Graph. The process seems to be working smoothly as the request returns a 200 status code and a significant amount of data is retrieved. However, when I attempt to insert the photo into an image tag, the browser refuses to display it. It appears that Graph returns the image as a JPEG binary, but I have struggled to find a method that successfully converts the binary into a format that can be displayed by the browser.

  • An attempt using btoa resulted in the following error:

    Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

  • Another approach involving a FileReader (using TypeScript and jQuery) provided a result, but the browser still failed to render the image:

//Where photo is the data as a string
let blob = new Blob([photo], { type: "image/jpeg" });
let reader = new FileReader();
reader.addEventListener("load", (e: any) => {
    let imgSrc = e.target.result;
    $("img").attr("src", imgSrc);
});
reader.readAsDataURL(blob);

  • Even trying to use URL.createObjectURL seemed to work, but the image was not displayed:

let blob = new Blob([photo], { type: "image/jpeg" });
let url = URL.createObjectURL(blob);
$("img").attr("src", url);

  • Experimenting with different values for the type property in the blob constructor, including various image formats and 'octet-binary', also turned out unsuccessful. The image is clearly a JPEG as evident from the "JFIF" characters seen when printing it out as a string in Chrome's debugger.
  • Even attempting a custom hex-to-base64 function found in the top answer to a Stack Overflow question failed to render the image: How to display binary data as image - extjs 4

$("img").attr("src", "data:image/jpeg;base64," + hexToBase64(photo));

  • Lastly, trying to embed the unmodified image binary as a data source also proved to be unsuccessful.

At this point, I have run out of ideas. Does anyone have any suggestions to resolve this issue?

Answer №1

Introducing my latest creation, a web app designed to showcase the Graph APIs in action - meet the Visual Graph Explorer. By logging in with your O365 credentials, you'll witness user photos being pulled down seamlessly. For those interested in diving deeper, feel free to explore the full source code on GitHub.

Delving into the code for displaying user photos, here's a snippet for reference. Angular is the framework of choice here, with a key emphasis on leveraging the createObjectUrl method to render response data as a URL for browser rendering. A near match to the second example can be seen below:

graphPersonPhotoDirective.js

function successCallback(response) {
    var url = window.URL || window.webkitURL;
    var blobUrl = url.createObjectURL(response.data);
    $scope.myPhoto = blobUrl;
    Cache.save(blobUrl, $scope.personId);
}

graph-person-photo.html

<div class="circular-container">
    <div class="circular" style="background-image: url('{{myPhoto}}')"></div>
</div>

Exploring the Visual Graph Explorer has been a pleasure. I trust this insight proves beneficial to you!

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

Is it feasible to link an Angular property value to the value of an HTML data attribute?

Can an Angular property value be bound to a data attribute on a template element? <h1 data-name="{{name}}">Hello from {{ name }}!</h1> Example Link After running the code, it results in the following error: Error in src/main.ts (11: ...

Issue with Angular Ionic HTTP promise functionality not performing as expected

My service retrieves data from an endpoint : Service.ts getAllProducts(){ return new Promise( (resolve, reject) => { this.apiService.get( this.allProducts, `/products`, {} ) .then( data => resolve( data.map( item => this.par ...

What could be causing the code to produce 4 elements instead of the expected 2?

I'm trying to understand why the code above is creating four new paragraphs instead of just two. Can someone please explain what exactly happens in the $("p").before($("p").clone()); part? <!DOCTYPE html> <html> <head> <script ...

What is the best way to extract the text inside a div element based on the input value in a

I attempted to extract the innerText of a div along with the input values within it. For instance: <div> My name is Shubham, I work for <input type="text"/> for the last 5 years.</div> My objective is to retrieve all the text ...

Navigating within a React application - rendering JSX components based on URL parameters

As I work on developing a web-app with a chapter/lesson structure, I have been exploring ways to handle the organization of lessons without storing HTML or React code in my database. One idea I had was to save each lesson as a .jsx file within a folder str ...

Retrieve information and auto-fill text boxes based on the selected dropdown menu option

UPDATED QUESTION STATUS I'm currently working with Laravel 5.7 and VueJs 2.5.*. However, I am facing a challenge where I need to automatically populate form textboxes with data from the database when a dropdown option is selected. Despite my efforts ...

Utilizing a package from your local computer

Due to my current circumstances, I am unable to utilize the npm publish command to release a package on the internet and subsequently use npm install. I also have no intention of publishing it on a remote server like nexus. Is there a method available to ...

typescript What is the best approach to searching within a nested array?

I am struggling to extract a specific value from a nested array within an array. Here is an example structure of my array: [ { ConcessionId: 1, ConcessionName: "Coyotes", KnownAs: [ { TeamId: 1, ...

React Native: The function `useContext.getItemsCount()` is returning a value of undefined, which is not an object

As a newcomer to React Native, I encountered an error when calling getItemsCount. *To view images, please click on the following links: https://i.sstatic.net/wbwjZ.png This snippet shows the code for CartIcon.js: import React, {useContext} from 'r ...

On Windows systems, where exactly does npm place its packages during installation when using Node version 10.x

Does anyone know where I can locate the locally installed npm modules when using NodeJS version 10? I have checked under C:\Users\MyUser\AppData\Roaming, but I cannot find the "npm" folder. ...

Updating by clicking with auto-prediction feature

I have implemented an autosuggestion feature to display results from a database table while typing in an HTML field, and I am looking to utilize JavaScript to post another value from the same row where the autosuggested values are stored. https://i.stack. ...

What about connecting mapStateToProps with a specific ID?

Currently, I have a basic function that fetches all Elements const mapStateToProps = ({elements}) => { return { elements: getElementsByKeyName(elements, 'visibleElements'), }; }; I want to modify it to something like this c ...

The functionality of the bootstrap Dropdown multiple select feature is experiencing issues with the Onchange

Creating a Bootstrap Multiple Select Drop Down with dynamically retrieved options from a Database: <select size="3" name="p" id="p" class="dis_tab" multiple> <?php echo "<option>". $row['abc'] ."</option>"; //Fetching option ...

Save the current state of the collapsible navigation menu

I developed a website for a friend, but I'm encountering an issue with my js/css vertical and collapsible menu. Every time I click a link, the new page loads and the entire menu collapses again. I've tried to figure out a way to "store" the infor ...

`Switching the selection in ng-selected`

I am having trouble toggling ng-selected options in Angular. I have tried the following approach: <select ng-model="datacut.ages" multiple> <option value="" disabled="disabled">Please Select</option> <option value="0-15" ng-clic ...

Problem with validation in jQuery not being compatible with Kendo Button (sample code provided in jsfiddle)

It took me some time to figure out that the reason jquery-validate wasn't functioning in my Kendo Mobile application was because my submit button was a Kendo Button. Check out this jsfiddle for illustration: DEMO <div id="phoneApp" style="displa ...

Retrieving data from a JSON file at 10-minute intervals with Ajax and visualizing it on Google's globe API

After downloading Armsglobe, a globe API provided by Google to draw lines in countries using their names, I noticed that the original code does not fetch JSON data periodically. I attempted to use a simple setTimeout() function in dataloading.js to address ...

having issues with my expressjs router functionality

Embarking on my MEAN stack journey, I have been immersing myself in tutorials. It has become clear that everyone does not approach the logic in the same way. However, I find myself stuck on two particular examples. Example One: // server.js var express = ...

NodeJS guide: Enabling cross-domain access for web services

Currently, I am developing a nodejs server and facing the challenge of needing to access additional services through ajax from a different domain. Can anyone provide guidance on how to bypass the cross-domain restriction within nodejs code? Please note th ...

Encountering Error when Attempting to Load Webpack Dependencies for Browser

I'm currently in the process of manually scaffolding an Angular 6 app (not using the CLI). Everything was going smoothly until I encountered a webpack error: ERROR in window is not defined After researching online, it seems like I may be missing som ...