Java接口返回BufferedImage时Angular10如何展示用户照片
对接Microsoft Graph用户照片接口的前后端实现
开发了一套调用Microsoft Graph获取用户照片的接口,初期的对接卡点为:不清楚Angular端如何处理接口返回结果,才能实现照片的正常展示。
初始实现版本
Java侧初始逻辑
最初Java端从Graph拉取图片流后直接转成BufferedImage返回,核心代码:
public BufferedImage getUserPhoto (String accessToken) throws IOException { IAuthenticationProvider mAuthenticationProvider; try{ mAuthenticationProvider=request->request.addHeader("Authorization",accessToken); }catch(Exception e){ throw new Error("Could not create a graph client: "+e.getLocalizedMessage()); } graphClient= GraphServiceClient.builder() .authenticationProvider(mAuthenticationProvider) .buildClient(); InputStream stream = graphClient .me() .photo() .content() .buildRequest() .get(); System.out.println("Stream"+ stream); BufferedImage image = ImageIO.read(stream); return image; }
该返回结构无法被前端直接解析渲染,存在对接障碍。
Angular侧初始逻辑
最开始Angular端发起普通GET请求,未指定响应解析类型,默认按JSON格式处理返回结果,核心代码:
getUserPhoto(){ return this.httpClient.get(`${API_URL}/graph/getPhoto`); };
该默认解析规则无法正确识别非JSON类的图片返回内容,无法正常展示照片。
最终落地解决方案
核心改造思路:Java侧将获取到的BufferedImage转换为Base64字符串后返回接口结果,Angular端接收字符串后拼接为可直接使用的图片地址,完成展示。
Java侧改造代码
拿到Graph返回的图片流转为BufferedImage后,将图片写入字节输出流得到原始字节数组,再编码为Base64字符串返回,注意及时关闭流资源:
BufferedImage image = ImageIO.read(stream); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(image, "jpeg", bos); byte[] imageBytes = bos.toByteArray(); BASE64Encoder encoder = new BASE64Encoder(); String imageString = encoder.encode(imageBytes); bos.close();
Angular侧改造代码
改造包含两个核心调整点:
- 发起请求时显式将
responseType设置为text,避免默认JSON解析破坏Base64字符串的原始内容 - 拿到Base64字符串后拼接为带MIME类型声明的Data URL,通过Angular的DomSanitizer绕过内置安全策略限制,完成图片地址的可渲染赋值
核心实现代码:
getPhoto(){ return this.httpClient.get(`${API_URL}/graph/getPhoto`,{ responseType: "text" }); } public getUserPhoto(){ this.graphService.getPhoto().subscribe( response => { let objectURL = 'data:image/jpeg;base64,' + response; this.photo = this.sanitizer.bypassSecurityTrustUrl(objectURL); }); }
内容的提问来源于stack exchange,提问作者nabeelh21
相关产品推荐
相关产品推荐

