簡體   English   中英

使用Angular 2從圖像URL獲取base64圖像

[英]get base64 image from image url using angular 2

我正在嘗試顯示其URL來自Flickr照片搜索API的圖像。 我想將這些圖像URL轉換為base64,以便將圖像存儲在會話存儲中,並且僅在會話存儲中不存在圖像時才調用Flickr API:

 export class AComponent { results: any[]; base64; constructor(private http: HttpClient, private jsonp: Jsonp, private router: Router, private storage: SessionStorageService) { if (!sessionStorage.getItem("results")) { this.http.get('https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=378060923d01ccb122bd53491163355d&tags=jungle&per_page=5&format=json&nojsoncallback=1').subscribe(data => { this.results = (<RootObject>data).photos.photo.map((photo) => { return { // url:`https://farm${photo.farm}.staticflickr.com/${photo.server}/${photo.id}_${photo.secret}_m.jpg`, base64: this.base64, // this line how can I get base64 image from the above url title: photo.title } }); sessionStorage.setItem("results", JSON.stringify(this.results)); }); } else { this.results = JSON.parse(sessionStorage.getItem("results")) } } } 

您應該在GET-Request設置中設置responseType: ResponseContentType.Blob ,因為這樣您就可以將圖像獲取為blob,並在以后將其轉換為base64編碼的源。 您上面的代碼不好。 如果您想正確執行此操作,請創建單獨的服務以從API獲取圖像。 因為在組件中調用HTTP請求不是很好。

這是一個工作示例:

創建image.service.ts並輸入以下代碼:

    getImage(imageUrl: string): Observable<File> {
        return this.http
            .get(imageUrl, { responseType: ResponseContentType.Blob })
            .map((res: Response) => res.blob());
    }

現在,您需要在image.component.ts創建一些函數以獲取圖像並將其顯示為html。

要從Blob創建圖像,您需要使用JavaScript的FileReader 這是創建新FileReader並監聽FileReader的load-Event的函數。 結果,此函數返回base64編碼的圖像,您可以在img src-attribute中使用該圖像:

imageToShow: any;

createImageFromBlob(image: Blob) {
       let reader = new FileReader();
       reader.addEventListener("load", () => {
          this.imageToShow = reader.result;
          // here you can save base64-image to session/localStorage
          localStorage.setItem('yourKey', this.imageToShow);
       }, false);

       if (image) {
          reader.readAsDataURL(image);
       }
}

createIamgeFromBlob() - createIamgeFromBlob() ,可以通過鍵將base64映像保存到sessionStorage / localStorage。 如果上面的示例不起作用,請嘗試將結果轉換為字符串。 例如: localStorage.setItem('yourKey', this.imageToShow.toString());

現在,您應該使用創建的ImageService從api獲取圖像。 您應該訂閱數據並將此數據提供給createImageFromBlob -function。 這是一個示例函數:

getImageFromService() {
      this.isImageLoading = true;
      this.imageService.getImage(yourImageUrl).subscribe(data => {
        this.createImageFromBlob(data);
        this.isImageLoading = false;
      }, error => {
        this.isImageLoading = false;
        console.log(error);
      });
}

現在,您可以像這樣在HTML模板中使用imageToShow

<img [src]="imageToShow"
     alt="Place image title"
     *ngIf="!isImageLoading; else noImageFound">
<ng-template #noImageFound>
     <img src="fallbackImage.png" alt="Fallbackimage">
</ng-template>

我希望此描述易於理解,並且可以在項目中使用。

loadImage(imageUrl) {
  const self = this;

  const xhr = new XMLHttpRequest()
  xhr.open("GET", imageUrl);
  xhr.responseType = "blob";
  xhr.send();
  xhr.addEventListener("load", function() {
      var reader = new FileReader();
      reader.readAsDataURL(xhr.response); 
      reader.addEventListener("loadend", function() {             
          self.base64Img = reader.result;
      });
  });
}

鏈接到朋克

為了讓the客工作,您需要一張帶cors有效圖像的圖像。 我使用了chrome擴展程序。

在示例代碼中,我將結果存儲在組件變量中。 編碼的64圖像位於reader.result中。

這里得到的答案

首先,您必須創建圖片網址

imgUrl = `https://farm${photo.farm}.staticflickr.com/${photo.server}/${photo.id}_${photo.secret}.jpg`

REF

然后獲得base64圖像

   function toDataURL(url, callback) {
          var xhr = new XMLHttpRequest();
          xhr.onload = function() {
            var reader = new FileReader();
            reader.onloadend = function() {
              callback(reader.result);
            }
            reader.readAsDataURL(xhr.response);
          };
          xhr.open('GET', url);
          xhr.responseType = 'blob';
          xhr.send();
        }

        toDataURL(imgUrl, function(dataUrl) {
          console.log('RESULT:', dataUrl)
        })

最終代碼

export class AComponent {

results: any[];
base64;
constructor(private http: HttpClient, private jsonp: Jsonp, private router: Router,
    private storage: SessionStorageService) {

    if (!sessionStorage.getItem("results")) {

        this.http.get('https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=378060923d01ccb122bd53491163355d&tags=jungle&per_page=5&format=json&nojsoncallback=1').subscribe(data => {
            let promises = (<RootObject>data).photos.photo.map((photo) => {
                return this.getBase64Photo(photo).then(base64Photo => {
                      return base64Photo;
                })
            }
            Promise.all(promises)
              .then(results => {
                this.results = results;
              })
              .catch(e => {
                console.error(e);
              })
            sessionStorage.setItem("results", JSON.stringify(this.results));
        });
    }
    else {

        this.results = JSON.parse(sessionStorage.getItem("results"))
    }

}

toDataURL(url, callback) {
      var xhr = new XMLHttpRequest();
      xhr.onload = function() {
        var reader = new FileReader();
        reader.onloadend = function() {
          callback(reader.result);
        }
        reader.readAsDataURL(xhr.response);
      };
      xhr.open('GET', url);
      xhr.responseType = 'blob';
      xhr.send();
}

getBase64Photo(photo){
    return new Promise((resolve, reject) => {
        let url =`https://farm${photo.farm}.staticflickr.com/${photo.server}/${photo.id}_${photo.secret}_m.jpg`;
        let base64Data;
        this.toDataURL(url, (data)=>{
            resolve({
            base64: base64Data, // this line how can I get base64 image from the above url
            title: photo.title
            })
        })
      });
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM