问题
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:
- You don't have to add
this
in your templates ($store
is enough). 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