渲染base64图像,当前返回空白 [英] Rendering a base64 image, currently comes back as blank

查看:152
本文介绍了渲染base64图像,当前返回空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将字符串存储在vuex中之前,我已经从Microsoft graphQL中提取了一个图像并应用了以下内容.

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}`"/>

我尝试将charset-utf-8添加到混合物中,并添加了一些变体,包括不同的图像类型,包括png和jpeg.

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

CSS类仅对图像进行四舍五入并添加一些阴影.

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. 您不必在模板中添加 this ( $ store 就足够了).
  2. 我怀疑在编译模板时,您的商店中不存在该值.您访问变量的方式不会使其反应.这意味着,如果在初次评估时它不是正确的值,则以后将不会更改.相反,您应该使用已计算的属性访问数据-这样,vue将附加一个setter和getter,这将允许该属性在运行时进行反应性更新:

  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}`;
  }
}

将图像数据编码为dataURL

如果要将图像数据转换为dataURL,可以将其用作图像标签的 src 值,则可以使用 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');
}

此功能假定您已经加载了图像.如果需要从URI加载图像,请将其包装在image.onload函数中.

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.

这篇关于渲染base64图像,当前返回空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆