Display Image From Http Response With Image Content Type
Solution 1:
var rawResponse = "�PNG...."; // truncated for example// convert to Base64var b64Response = btoa(rawResponse);
// create an imagevar outputImg = document.createElement('img');
outputImg.src = 'data:image/png;base64,'+b64Response;
// append it to your pagedocument.body.appendChild(outputImg);
Solution 2:
The accepted answer didn't worked for me. So here's my solution:
- I'm using
fetch
to download image, so I need to read response asblob
:
let data;
fetch(url).then(response => {
response.blob().then(blobResponse => {
data = blobResponse;
})
});
- Displaying blob as image:
const urlCreator = window.URL || window.webkitURL;
document.getElementById('myImage').src = urlCreator.createObjectURL(data);
Solution 3:
I would convert the image to base64 using canvas toDataURL and then append it to the DOM like so:
var rawResponse = 'PNG'; // This is your response objectvar encodedResponse = btoa(rawResponse);
var img = newImage();
var container = document.getElementById('newImg');
img.src = 'data:image/gif;base64,' + encodedResponse;
img.onload = function() {
container.appendChild( img );
};
More information on btoa
Solution 4:
we can get response and bind it form my HTML.
1) .ts file page : -
imageData : any ;
response => {
var b64Response = btoa(response);
this.imageData = 'data:image/png;base64,' + b64Response;
}
2) .html file page:
<img [src]="imageData"class="img-thumbnail">
Solution 5:
Solution
use the blob
const response = awaitfetch(`...`) const responseBlob = await response.blob() const img = document.createElement('img') img.src = URL.createObjectURL(responseBlob) document.querySelector(`body`).append(img)
solution 2
get the URI.scheme.data from blob.
The below example (case 2) will show you the details.
Example
This example is to get the image from some repository of GitHub.
/**
* @param {int} solutionNumber: I provide two solutions both can achieve.
* @param {string} owner
* @param {string} repo
* @param {string} path
* @param {string} branch: branch name or you can use SHA1
* @param {string} token: Used while your repository is private. https://github.com/settings/tokens
*/asyncfunctionShowGithubImg(solutionNumber, owner, repo, path, branch = "master", token = "") {
const response = awaitfetch(`https://api.github.com/repos/${owner}/${repo}/contents/${path}?ref=${branch}`, {
// method: "GET",headers: {
accept: 'application/vnd.github.v3.raw',
// authorization: `token ${token}`
}
})
if (!response.ok) {
const errMsg = await response.text()
throwError(`${response.statusText} (${response.status}) | ${errMsg} `)
}
const responseBlob = await response.blob()
const img = document.createElement('img')
switch (solutionNumber) {
case1:
img.src = URL.createObjectURL(responseBlob)
breakcase2:
let uriData = ""
blob2bas64 = async (blob) => {
const promise = newPromise((resolve, reject) => {
const reader = newFileReader()
reader.onload = function () { // use promise to wait until onload finishedconsole.log(this.result) // you can see its media type is: application/vnd.github.v3.raw // https://docs.github.com/en/rest/overview/media-types
uriData = this.result// <--- `this.result` contains a base64 data URIresolve()
}
reader.readAsDataURL(blob)
})
await promise
}
awaitblob2bas64(responseBlob)
img.src = `${uriData}`break
}
document.querySelector(`body`).append(img)
}
for (const solutionNumber of [1, 2]) {
ShowGithubImg(solutionNumber, "CarsonSlovoka", "excel", "app/urls/static/app.ico", "807dd79")
}
URI
@Lostsource's answer mentions Uniform Resource Identifier Since this question only asks about images, but some people have other formats (image/jpeg) In fact, the format of URI.scheme.data is
data:<mediatype>[;base64],<data>
👆 you can see it on Uniform Resource Identifier
You just need to know the mediatype
(common mediatype list).
For example image/jpeg
data:image/jpeg;base64,<data>
Post a Comment for "Display Image From Http Response With Image Content Type"