Monday, March 25, 2013

servlet with image upload and resizing

Continuing my recent trend of small notes from the trenches, to my future self:

my next Proof of Concept was image uploading. I was able to use the example at http://www.codejava.net/java-ee/servlet/code-example-file-upload-servlet-with-apache-common-file-api pretty much verbatim.

In the future I'd need to store a byte array, but the FileItem object has a .get() function that does just that.

For scaling there's the lovely library imgscalr. I then also had to learn about stuff like java.awt.image.BufferedImage and javax.imageio.ImageIO. The guts of my variation on the FileUploadServlets ended up looking like
InputStream instream = item.getInputStream();
BufferedImage origImg = ImageIO.read(instream);
BufferedImage smallImg = resize(origImg,100);
ImageIO.write(smallImg, "jpg", storeFile);
(I was assuming the filename already ended in ".jpg")

The java.awt and java.io are said to show up in "rt.jar", and on our development system they seemed to be included in the j2ee.jar runtime dependency I was using.

Imgsclr also does cropping; that would imply more of a need for a nice UI, though, perhaps using Jcrop. (Probably beyond the scope of my curent project.)

In the scope of my current project is storing stuff in the database rather than the file system; Nick who is handling the DB side says I can store byte arrays, and according to this page that will look something like
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( originalImage, "jpg", baos );
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();


(I'm not sure if that is the most efficient use of Streams, but should be good enough for our purposes now.)

Man. Do servlets count as UI? Sometimes I wonder.

No comments:

Post a Comment