Rendering a base64 image, currently comes back as blank

∥☆過路亽.° 提交于 2021-02-11 14:52:14

问题


I've pulled an image from Microsoft graphQL and applied the following before storing the string in vuex.

Buffer.from(image).toString('base64')

Inside my component I'm trying to render the image in the following way

<img class="shadow avatar border-white" :src="`data:image/jpg;base64,${this.$store.state.user.profilePhoto}`"/>

I've tried adding the charset-utf-8 into the mix and a few variations including different image types including png and jpeg.

The CSS class simply rounds the image and adds a bit of shadow.

At the moment I'm getting a transparent circle and no image to be found.

Is there another way I need to encode the image before trying to render it?


回答1:


There are a couple things you could improve:

  1. You don't have to add this in your templates ($store is enough).
  2. I suspect your the value is not present in your store when the template is compiled. The way you access the variable will not make it reactive. That means if it is not the correct value when it is first evaluated, it will not change later. Instead you should access your data with a computed property - this way vue will attach a setter and getter, which allows the property to reactively update at at runtime:

    <img :sry="imgSrc" />
    
    
    computed: {
      profileImg() {
        return this.$store.state.user && this.$store.state.user.profilePhoto;
      },
    
      imgSrc() {
        return 'data:image/jpg;base64,${this.profileImg}`;
      }
    }
    

Edit: Encode Image data to dataURL

If you want to convert image data into a dataURL which you can use as src value for image tags you can do it with an HTMLCanvasElement:

function imageToDataURL(image) {
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d');
  context.drawImage(image, image.width, image.height);
  return = canvas.toDataURL('image/png');
}

This function assumes you already have a loaded image. If you need to load your image from an URI, wrap it in an image.onload function.



来源:https://stackoverflow.com/questions/58199422/rendering-a-base64-image-currently-comes-back-as-blank

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!