如何使用angularjs在网页中显示图像?

时间:2016-10-14 13:13:41

标签: angularjs mongodb

我已经知道如何使用angularjs和java在mongodb中保存图像以将其保存在我的mongodb中,

我需要从mongodb获取已保存的图像,并使用AngularJS将其显示在html页面中。

这是我获取图像的控制器

@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getById(@PathParam("id") String id) throws IOException
{
    Response response = null;
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB mongoDB = mongoClient.getDB("sampleDB");
    DBCollection collection = mongoDB.getCollection("filestore");
    BasicDBObject query = new BasicDBObject();
    ObjectId oid = new ObjectId(id);
    query.put("_id", oid);
    GridFS fileStore = new GridFS(mongoDB, "filestore");
    GridFSDBFile gridFile = fileStore.findOne(query);
    InputStream in = gridFile.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int data = in.read();
    while (data >= 0)
    {
    out.write((char) data);
    data = in.read();
    }
    out.flush();
    ResponseBuilder builder = Response.ok(out.toByteArray());
    builder.header("Content-Disposition", "attachment; filename=");
    response = builder.build();
    return response;
}

这是我获取图像的角度

var userImagePromise = $http.get("../api/s3/" + $scope.user.profileImage[0].id);
userImagePromise.success(function(data, status, headers, config) {
    $scope.imageData = data;
});
userImagePromise.error(function(data, status, headers, config) {
});

这是我用于显示图片的html

<img id="userProfileImg" height="150px" width="150px" ng-src="data:image/png;base64,{{imageData}}">

如果我只是将链接放到浏览器我在octect-stream

中得到了这个输出

PNG.....

如何在html中显示图像?我的代码中出现任何错误?

Image for getting output

1 个答案:

答案 0 :(得分:0)

我认为您的base64代码没有正确转换图像,因此请检查我的代码,它可能会对您有所帮助。

import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import javax.imageio.ImageIO;




BufferedImage buffimage = ImageIO.read(new File(imagePath));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(buffimage, "png", baos);
String img = Base64.encode(baos.toByteArray());

将此img变量发送到angularjs代码。