ionic-framework - Ionic 不显示从后端加载的图像

标签 ionic-framework ionic4

我必须从服务器请求二进制图像,但我需要额外的 header 和授权。因此我只能在后端执行此操作。在我使用 ionic native HTTP 收到图像后,我尝试多次显示图像,但都没有成功。

1)我尝试将二进制数据设置为这样的字段:

this.unit.img(this.unitInfo.logo).then( (r) => {
  this.logo = r.data;
}

在 html 上:
  <ion-img [src]="logo"></ion-img>

2)我也尝试将 img 转换为 base64 img,如下所示:
 this.unit.img(this.unitInfo.logo).then( (r) => {
      var imageData = btoa(r.data);
      this.logo = "data:image/png;base64,"+imageData

并且:
  <ion-img [src]="logo"></ion-img>

要显示图像,但这些都不起作用:皱眉:

不知道这是否有用,但这是用于获取图像的代码:
make_get_img(path, options){
    let headers = Object.assign({
        'Accept': '*/*',
        'Content-Type': '*/*'
        }, options.headers || {})

    if(this.token){
        headers = Object.assign(headers, {
            'token': this.token
        })
    }

    let url = this.getUrlWithParams(path, options.urlParams)


    return this.http.get(url, { responseType: 'blob' }, headers);
}

我在其他网站上测试了该字符串,但收到一条消息,指出转换错误。

我不知道如何解决这个问题。
请帮忙。

编辑

我也试过像这样转换 img:
    var u8 = new Uint8Array(r.data);
    console.log(u8)

    var b64encoded = btoa(String.fromCharCode.apply(null, u8));
    var mimetype="image/png"; // or whatever your image mime type is

    this.logo = "data:"+mimetype+";base64,"+b64encoded;
    this.logo =  this.logo.replace(new RegExp(' ', 'g'), '+');

还试过:
  var imageData = btoa(r.data);

  let objectURL = 'data:image/png;base64,' + imageData;
  this.logo = this.sanitizer.bypassSecurityTrustUrl(objectURL);


  console.log(this.logo)

enter image description here

最佳答案

this.unit.img(this.unitInfo.logo).then( (r) => {
      var imageData = btoa(r.data);
      this.logo = "data:image/png;base64,"+imageData
 this.logo =  this.logo.replace(new RegExp(’ ', ‘g’), ‘+’);

你的 base64 编码图像中的所有“+”都被一个空白字符替换了......所以如果你只是把它们放回去......有一个错误......

这为我修复了错误,希望它也适用于你......

since you are getting error while displaying the image you can use DomSanitizer... in also in your ts file add



ts
    import { DomSanitizer } from "@angular/platform-browser";
     constructor(
    private DomSanitizer: DomSanitizer
  ) {}

html
<img
        [src]="DomSanitizer.bypassSecurityTrustUrl(base64Image)"
        *ngIf="base64Image"
        alt="Ionic File"
        width="300"
      />

关于ionic-framework - Ionic 不显示从后端加载的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57412128/

相关文章:

ionic4 - 无法添加任务 'processDebugGoogleServices',因为具有该名称的任务已存在

ionic-framework - Ionic 2 将按钮标签向左对齐

android - ionic /电容器 - PushNotiifcations - Android - “notification” + “data” 消息

javascript - 带有谷歌地图和 Ionic 3 的空白页

angular - 如何使用 Ionic 4 创建 Accordion 列表?

angular - Ionic 4 在选项卡之间共享数据

ionic-framework - 在 ionic cordova 构建 android 上的 ionic 中,JDK 1.8 的要求检查失败

javascript - Angular 自定义验证器不反射(reflect) View 中的更改

html - 创建水平滚动和环绕元素

angular - ionic 4 - Angular 6 : How to control Ionic router history to stop cache a view component?