gpt4 book ai didi

java - Angularjs/Java - 从休息服务方法获取图像

转载 作者:行者123 更新时间:2023-12-05 07:47:04 25 4
gpt4 key购买 nike

我的 java web 应用程序有一个 rest 服务方法并返回一个输入流图像。

@GET
@Path("/image/{id}")
@Produces("image/png")
public Response buscarFoto(@PathParam("id") Long id,
@Context HttpHeaders header,
@Context HttpServletResponse response) {
byte[] bytes = null;
bytes = yakifreeService.getImageStream(id);
ByteArrayInputStream in = new ByteArrayInputStream(bytes);


response.setContentType("images/png");
response.setHeader("Content-Type", "image/png");
response.setHeader("Content-Disposition", "inline; filename=\"" + "image.png" + "\"");

try {
OutputStream out = response.getOutputStream();
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
} catch (IOException ex) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).type(MediaType.TEXT_HTML).build();
}

return Response.ok().build();

Angularjs 客户端获取输入流图像如下

Image.getImage({ id: $scope.model.image.id }).$promise.then(function (result){
if (result) {
$scope.model.image.dataURL = 'data:image/png;base64,' + result;
}
});


function(yakifree) {
return yakifree.factory("Image", ["$resource", "$rootScope",
function($resource, $rootScope) {
var Image = $resource($rootScope.contextApp + '/rest/image/:id', { }, {
getImage: { method:'GET', params: {}, isArray: false }

});

return Image;
}]);
});

和 HTML 显示

<img data-ng-src="{{model.image.dataURL}}" width="120" height="120">

问题是 HTML 不显示图像。 javasript 中的结果变量的值为:

Resource {0: "�", 1: "P", 2: "N", 3: "G", 4: "
", 5: "↵", 6: "", 7: "↵", 8: "

有人可以帮助我吗?谢谢!

最佳答案

对我来说,下一个方法是正确的

    $resource(endpoint + 'images/:id', null, {
getImage: {
method: 'GET',
responseType: 'arraybuffer',
transformResponse: function(data) { return { data : data }}
}
})
...
const response = await resource.getImage({id}).$promise;
const binary = btoa(String.fromCharCode.apply(null, new Uint8Array(response.data)));
const img = 'data:image/png;base64,'+ binary;

...

<img src={img}/>

关于java - Angularjs/Java - 从休息服务方法获取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40131743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com