I found this code in a an old thread (http://forum.java.sun.com/thread.jspa?forumID=5&threadID=229236) and edited it slightly (to work in servlet). Now everytime I run it I get an ImageFormatException with the message "Not a JPEG file: starts with 0xff 0xd9". This occurs at:
"bi1 = decoder.decodeAsBufferedImage();"
Any help would be greatly appreciated.
try {
URL url = new URL("http://ec1.images-amazon.com/images/I/318NADVTADL.jpg");
URLConnection conn = url.openConnection();
BufferedImage bi1 = null;
InputStream inst=conn.getInputStream();
int size=inst.available();
byte[]b=new byte[size];
ByteArrayInputStream in = new ByteArrayInputStream(b);
JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
bi1 = decoder.decodeAsBufferedImage(); //ERROR LINE
File file = new File("c://test/test.jpg");
FileOutputStream outer= new FileOutputStream(file);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outer);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi1);
param.setQuality(1.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(bi1);
in.close();
outer.close();
b=null;
} catch (Exception ex) {
return;
}