0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

getRealPath is not portable
is the image being generated ? If not you can use stackoverflow.com/questions/8582577/… . It can be used even if the image is generated but you have to know its name.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.