使用Angular 2从图像URL获取base64图像 [英] get base64 image from image url using angular 2

查看:595
本文介绍了使用Angular 2从图像URL获取base64图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试显示其URL来自Flickr照片搜索API的图像.我想将这些图像URL转换为base64,以便将图像存储在会话存储中,并且仅在会话存储中不存在图像时才调用Flickr API:

I'm trying to display images that their URLs comes from Flickr photo search API. I want to convert these image URLs to base64 so I can store the images in Session Storage and only call Flickr API if images do not exist in Session Storage:

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请求不是很好.

You should set responseType: ResponseContentType.Blob in your GET-Request settings, because so you can get your image as blob and convert it later da base64-encoded source. You code above is not good. If you would like to do this correctly, then create separate service to get images from API. Beacuse it ism't good to call HTTP-Request in components.

这是一个可行的示例:

创建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.

Now you need to create some function in your image.component.ts to get image and show it in html.

要从Blob创建图像,您需要使用JavaScript的FileReader. 这是创建新的FileReader并侦听FileReader的load-Event的函数.结果,此函数返回base64编码的图像,您可以在img src-attribute中使用该图像:

For creating an image from Blob you need to use JavaScript's FileReader. Here is function which creates new FileReader and listen to FileReader's load-Event. As result this function returns base64-encoded image, which you can use in 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() -Function中,可以通过密钥将base64映像保存到sessionStorage/localStorage.如果上面的示例不起作用,请尝试将结果转换为字符串.例如:localStorage.setItem('yourKey', this.imageToShow.toString());.

In createIamgeFromBlob()-Function you can save your base64-image to sessionStorage/localStorage by key. If the example above doesn't work, try to convert the result to string. For example: localStorage.setItem('yourKey', this.imageToShow.toString());.

现在,您应该使用创建的ImageService从api获取图像.您应该订阅数据并将此数据提供给createImageFromBlob -function.这是一个示例函数:

Now you should use your created ImageService to get image from api. You should to subscribe to data and give this data to createImageFromBlob-function. Here is an example 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变量:

Now you can use your imageToShow-variable in HTML template like this:

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

我希望此说明易于理解,并且可以在您的项目中使用.

I hope this description is clear to understand and you can use it in your project.

这篇关于使用Angular 2从图像URL获取base64图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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