Skip to content Skip to sidebar Skip to footer

Display Image From Http Response With Image Content Type

Let's say I have url and don't know what it will return. I perform ajax call to that url with javascript and get the content. So I test it's content-type and decide how to show res

Solution 1:

var rawResponse = "�PNG...."; // truncated for example

// convert to Base64
var b64Response = btoa(rawResponse);

// create an image
var outputImg = document.createElement('img');
outputImg.src = 'data:image/png;base64,'+b64Response;

// append it to your page
document.body.appendChild(outputImg);

Solution 2:

The accepted answer didn't worked for me. So here's my solution:

  1. I'm using fetch to download image, so I need to read response as blob:
let data;
fetch(url).then(response => {
  response.blob().then(blobResponse => {
    data = blobResponse;
  })
});
  1. 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 object
var encodedResponse = btoa(rawResponse);

var img = new Image();
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

  • solution 1

    const response = await fetch(`...`)
    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
 */
async function ShowGithubImg(solutionNumber, owner, repo, path, branch = "master", token = "") {
  const response = await fetch(`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()
    throw Error(`${response.statusText} (${response.status}) | ${errMsg} `)
  }

  const responseBlob = await response.blob()

  const img = document.createElement('img')

  switch (solutionNumber) {
    case 1:
      img.src = URL.createObjectURL(responseBlob)
      break
    case 2:
      let uriData = ""
      blob2bas64 = async (blob) => {
        const promise = new Promise((resolve, reject) => {
          const reader = new FileReader()
          reader.onload = function () { // use promise to wait until onload finished
            console.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 URI
            resolve()
          }
          reader.readAsDataURL(blob)
        })
        await promise
      }

      await blob2bas64(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"