使用Angular 2从图像URL获取base64图像

编程入门 行业动态 更新时间:2024-10-22 21:34:18
本文介绍了使用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('api.flickr/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:`farm${photo.farm}.staticflickr/${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()); }

现在,您需要在imageponent.ts中创建一些函数以获取图像并将其显示为html.

Now you need to create some function in your imageponent.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图像

本文发布于:2023-07-27 00:14:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1219177.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图像   Angular   URL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!