return 1*1 pixel image in response play scala

2019-08-09 11:43发布

问题:

i need to return a same dummy image of 1*1 pixel in every response. I am using bufferArray to do this, my code snipet is as follow :

val image: BufferedImage = ImageIO.read(new File("public/images/dummy.png"));
val baos: ByteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);

Ok(baos.toByteArray).as("image/png")

after some time server throws error, java.io.excp too many files open. please help, is there any another way to do this ?

i have put that imagebuffer part in another object (i.e. object abc{}) and using it as abc.baos. but the error is same.

回答1:

You should be able to just serve the file as a response. Play has a responsewriter for files, so no need for the ByteArrayBuffer. If you do so Play should also close the file for you after it was being served.

Also checkout my comment on caching under your main post



回答2:

You can just use:

Ok.sendFile(new File("public/images/dummy.png"))