Reputation: 1
I like to access an image from the web/images
directory. I like to access this image in the spring controller
, so I can convert this image to byte[]
. I am creating a chart and this image is part of the chart display. So, I am using this byte[]
to construct Graphic2d object
. Closest I have got to it is using this:
FileSystemResource resource = new FileSystemResource("images/"+imageName);
Currently, I have stored this image in the package structure. I like to do better than this. I like to read directly from web/images
directory. Please give me some advice, Thanks.
Upvotes: 0
Views: 2421
Reputation: 434
The more elegant way is let your controller implement ServletContextAware
so as your controller can injecte ServletContext
instance, then you should use:
InputStream stream = servletContext.getResourceAsStream("/images/image.jpg");
int bytesRead;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
//process image data, i.e. write to sompe place,etc.
}
//close the stream
stream.close();
BTW, as for servletContext.getRealPath, different servlet container might have different implementation, and it might not work after project packaged to a war file. so, it's recommended to use getResourceAsStream.
Upvotes: 1
Reputation: 5868
Well you can use servlet context
to get the path to web/images
. Use following code:
File file=new File(request.getSession().getServletContext().getRealPath("images/file.jpg"));
Note: Here I am utilizing request
i.e. HttpServletRequest
.
Upvotes: 0