BASE64成像角2

时间:2016-08-07 10:00:36

标签: image angular base64

我正在尝试使用角度2来显示从远程服务器获取的图像。

在我的组件中,我有一个对象,它是一个“university_info”对象,是我的模型。

export class myClass
{
    university_info : university_info;
}
myFunction()
{
    this.university_info = new university_info(responseFromServer[image])
}

export class university_info
{
    imageBase64 : string
    constructor(image : string)
    {
        this.imageBase64 = image
    }
}

一切正常。我得到base64图像,但当我尝试以这种方式在HTML中显示它时:

  <img [src]="'data:image/jpg;base64,'+university_info.imageBase64" />

这就是我得到的:

enter image description here

enter image description here

enter image description here

7 个答案:

答案 0 :(得分:28)

我觉得这个帖子缺乏具体的例子,这让我有些困难:

导入DomSanitizer:

import { DomSanitizer } from '@angular/platform-browser';

在构造函数中定义:

constructor(private _sanitizer: DomSanitizer) { }

清理要作为图像源传递的Base64字符串(使用trustResourceUrl):

this.imagePath = this._sanitizer.bypassSecurityTrustResourceUrl('data:image/jpg;base64,' 
                 + toReturnImage.base64string);

绑定到html:

<img [src]="imagePath">

答案 1 :(得分:11)

您可以尝试使用_sanitizer.bypassSecurityTrustUrl告诉角度src值是否安全。从角度看这个类:

class DomSanitizationService {
    sanitize(context: SecurityContext, value: any) : string
    bypassSecurityTrustHtml(value: string) : SafeHtml
    bypassSecurityTrustStyle(value: string) : SafeStyle
    bypassSecurityTrustScript(value: string) : SafeScript
    bypassSecurityTrustUrl(value: string) : SafeUrl
    bypassSecurityTrustResourceUrl(value: string) : SafeResourceUrl
}

并且是安全html的一个例子:

export class AppComponent  {

    private _htmlProperty: string = '<input type="text" name="name">';

    public get htmlProperty() : SafeHtml {
       return this._sanitizer.bypassSecurityTrustHtml(this._htmlProperty);
    }

    constructor(private _sanitizer: DomSanitizationService){}
}

答案 2 :(得分:10)

请附上一个正确的示例,说明如何在Angular 2/4中的Base64中上传图像及其显示。实际的base64字符串被转储到调试器控制台中,当然也可以存储在数据库等中。

import { Component, OnInit } from '@angular/core';
// Base 64 IMage display issues with unsafe image
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-test',
  template: `
            <h1>Test 001 </h1>

          <div class="form-group">
            <label>Image</label>
            <input type="file" class="form-control" accept="application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint,
            text/plain, application/pdf, image/*" (change)="changeListener($event)">
          </div>

          <img *ngIf="base64Image" [src]="domSanitizer.bypassSecurityTrustUrl(base64Image)" />
    `,
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  private base64Image: string;

  constructor(private domSanitizer: DomSanitizer) { }

  ngOnInit() {
  }

  changeListener($event): void {
    this.readThis($event.target);
  }

  readThis(inputValue: any): void {
    var file: File = inputValue.files[0];
    var myReader: FileReader = new FileReader();

    myReader.onloadend = (e) => {
      this.base64Image = myReader.result;
      console.log(this.base64Image);
    }
    myReader.readAsDataURL(file);
  }

}

答案 3 :(得分:4)

您必须确保university_info.imageBase64字符串类型,然后您的代码才能生效。

DEMO http://plnkr.co/edit/pI35tx9gXZFO1sXj9Obm?p=preview

import {Component,ViewChild,Renderer,ElementRef,ContentChildren} from '@angular/core';

@Component({
  selector: 'my-app',

  template:   `
  <img [src]="'data:image/jpg;base64,'+imagePath"/> 
  `

})
export class App {
  imagePath:string="iVBORw0KG...";
}

答案 4 :(得分:4)

解决方案:只需在您的图片代码中使用'data:image/jpg;base64',就像这样

<img src="{{'data:image/jpg;base64,' + imagePath}}" />

答案 5 :(得分:2)

我想提出一个基于@gatapia提供的替代解决方案。

建议的解决方案是使用@ViewChild装饰器标签(请参阅此处的文档https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html),检索组件中的元素引用,并直接设置值,如下面的代码片段所示。需要注意的是,通过ViewChild引用的元素应该使用#绑定到本地变量,如下面的代码所示。

同样,正如ElementRef文档所解释的那样,直接使用ElementRef仍会暴露使用DomSanitizer时存在的XSS风险。

@Component({
  template: `
    <div>
      <img #imgRef> // Note that the #imgRef reference is required to be identified by Angular
    </div>
  `,
})
export class MyComponent implements OnInit {
  src:string;
  @ViewChild('imgRef') img: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Ni44LDE4Mi42aDBoMjEuN2gwbDExLjctMjkuMmg0OS40bDExLjcsMjkuMmgwaDIxLjdoMEwxMjUsNTIuMUwxMjUsNTIuMUwxMjUsNTIuMUwxMjUsNTIuMQ0KCQlMMTI1LDUyLjF6IE0xNDIsMTM1LjRIMTA4bDE3LTQwLjlMMTQyLDEzNS40eiIvPg0KPC9nPg0KPC9zdmc+DQo=';
  }

  ngOnInit() {
    // Sets the value of the element
    this.img.nativeElement.src = this.src;
  }
}

以下plunkr提供了上述https://plnkr.co/edit/JXf25Pv8LqrFLhrw2Eum?p=preview

的工作代码段

答案 6 :(得分:1)

这个问题获得了很高的谷歌排名,所以我想我会把我的发现放在这里。使用数据绑定来设置图像的[src]属性可能会有问题,尤其是在某些较旧的移动设备上。因此,如果使用sanitizer + binding方法存在性能问题,则必须直接使用DOM设置src属性:

constructor(private el: ElementRef) {}

...

public imageChanged(base64: string) {
  const im: HTMLImageElement = this.el.nativeElement.querySelector('#imgid'); 
  im.src = data;
}

这可能很难看,但它闪电般快。