Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Write an image from URL to file error

843807Oct 1 2007 — edited Oct 3 2007
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;
        }
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 31 2007
Added on Oct 1 2007
2 comments
120 views