Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

playframework 2.0 - Displaying image object from controller in the browser

I use playframework 2.2.1 with Java,
I am trying to pass BufferedImage or ByteArray or ByteArrayInputStream
to view template in order to display it in browser directly from memory,
without saving to server storage.
in my view template I request an image:

<img src="@{Application.getImage()}"/>

my Application controller:

public static Result getImage() throws IOException{  
    BufferedImage image = ImageIO.read(new File("public/img/1.jpg"));  
    //some image manipulations  
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    ImageIO.write(image, "jpg", baos);  
    return ok(baos.toByteArray()).as("image/jpg");  
}

in generated html I get:

<img src="SimpleResult(200, Map(Content-Type -&gt; image/jpg))">

I've found some info about this topic (one, two, three, four),
but it is usually related to older versions, or Scala versions of play.
Please suggest anything or point to my mistake,
Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For byte array images here's my solution (based on other solutions in stackoverflow):

The Controller:

public static Result getImage(Long id) {
    Entity entity = Entity.find.byId(id);
    ByteArrayInputStream input = null;

    if (entity.getImage() != null) {
        input = new ByteArrayInputStream(entity.getImage());
    } else {
        try {
            byte[] byteArray;
            File file = Play.getFile("/public/images/no_photo.jpg", Play.current());
            byteArray = IOUtils.toByteArray(new FileInputStream(file));
            input = new ByteArrayInputStream(byteArray);
        } catch (Exception e) {

        }
    }

    return ok(input).as("image/jpeg");
}

The routes file:

GET     /entity/image/:id       controllers.Entities.getImage(id:Long)

The view:

<img src=@{routes.Entities.getImage(entity.getId())}>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...