【问题标题】:Ionic doesnt display image loaded from backend离子不显示从后端加载的图像
【发布时间】:2019-12-16 03:17:41
【问题描述】:

我必须从服务器请求二进制图像,但我需要额外的标头和授权。因此我只能在后端执行此操作。在我使用 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)

【问题讨论】:

  • 尝试简单的img 标签。 ion-img 标签有问题。
  • 感谢您的回答。试过了,但结果相同:(还有其他想法吗?

标签: ionic-framework ionic4


【解决方案1】:
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 编码图像中的所有“+”都被替换为空白字符......所以如果你只是把它们放回去......有一个错误......

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

因为您在显示可以使用的图像时遇到错误 DomSanitizer...也在你的ts文件中添加

ts

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

html

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

【讨论】:

  • 谢谢你的回答,我很确定它会帮助别人,但没有为我解决:(你还有其他想法吗?
【解决方案2】:

URL.createObjectURL 可用于创建一个 URL,该 URL 表示在 make_get_image 返回的 Blob 的 Observable。

在您的代码中,您已经访问了 blob 中的 data,但这具有 undefined 值,因为 make_get_image 的返回值是 Blob 的可观察值。

您应该订阅 / 从 Observable 解析 blob 并创建一个 URL。例如,

this.unit.img(this.unitInfo.logo).then((b: Blob) => {
  this.logo = URL.createObjectURL(b);
});

请注意,您可能需要也可能不需要 set the width and height properties&lt;ion-image&gt; 或在标签中应用 CSS 类选择器的样式属性。

【讨论】:

  • 还没测试,会尽快反馈,谢谢=]
猜你喜欢
  • 2017-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-07
  • 1970-01-01
  • 1970-01-01
  • 2019-12-15
  • 1970-01-01
相关资源
最近更新 更多