Why is my svg image not found while the url is correct?

Viewed 582

I'm using https://identicon-api.herokuapp.com/ to embed identicons in my page. You can choose either SVG or PNG. PNG works just fine, but for performance reasons, I want to use SVG. But when I use SVGs, the image isn't found, and the alt-text is displayed.

Nevertheless, the URL is valid, and when I open the image in a new tab, it's rendered correctly.

<img
  v-if="iconsenabled"
  style="max-width:1.75em"
  :src="'https://identicon-api.herokuapp.com/'+e.author+'/2000?format=svg'"
  :alt="e.author+`'s identcon.`"
  :title="e.author+`'s identicon. Toggle 'show icons' to see the name instead`"
/>

(BTW, Yes, I'm using Vue, but that doesn't affect anything)

1 Answers

The SVG has an incorrect MIME type set by the server. <img> requires the MIME type to be image/svg+xml, but https://identicon-api.herokuapp.com/ currently sets it to text/html, which causes a loading error:

For reference, here's a sample SVG with the proper MIME type that renders correctly in an <img>:

<img src="https://upload.wikimedia.org/wikipedia/commons/4/42/Sample-image.svg" width="200">

As a workaround, you could fetch the SVG, convert it to a base64 string, and use that as a data URL:

<img :src="'data:image/svg+xml;base64,' + __SVG_BASE64__">

Example:

new Vue({
  el: '#app',
  data: () => ({
    myImgUrl: ''
  }),
  mounted() {
    fetch('https://identicon-api.herokuapp.com/tony19/2000?format=svg')
      .then(resp => resp.text())
      .then(text => this.myImgUrl = 'data:image/svg+xml;base64,' + btoa(text))
  }
})
<script src="https://unpkg.com/vue@2.6.12"></script>

<div id="app">
  <img :src="myImgUrl" width="200" height="200">
</div>

Related