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?