Is there anyway to scale an image then display in jsp page? When retrieve and display the images, I want to show all photos in same size. is there any API can do it? I have searched from google, those I found was about scaling images byusing tookit but can’t works in web application.
Share
You can use the builtin Java 2D API for this (basic Sun tutorial here).
Basically, you need to create a Servlet which gets an
InputStreamof the original image in thedoGet()method, passes it through the Java 2D API and then writes it to theOutputStreamof the HTTP response. Then you just map this Servlet on a certainurl-patterninweb.xml, e.g./thumbs/*and call this Servlet in thesrcattribute of the HTML<img>element.Here’s a basic kickoff example (you still need to handle unexpected conditions yourself the way you want):
With the servlet mapped in
web.xmlas follows:This can be used as follows:
Note: no, this cannot be done with JSP alone since it’s a view technology unsuitable for this task.
Note 2: this is a pretty expensive (CPU intensive) task, keep this in mind. You may want to consider to cache or pregenerate the thumbs beforehand yourself.