通过异常将字节数组转换为jpg图像文件

时间:2014-05-01 04:31:53

标签: java file-io bytearray jpeg

嗨我有一个字节数组,我正在转换为jpg图像,但是如下所示给出异常请解释我这是问题。

ByteArrayInputStream bis = new ByteArrayInputStream(someByteArray);
                Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg");

            //ImageIO is a class containing static methods for locating ImageReaders
                //and ImageWriters, and performing simple encoding and decoding. 
                ImageReader reader = (ImageReader) readers.next();
                Object source = bis;
                ImageInputStream iis = ImageIO.createImageInputStream(source);
                reader.setInput(iis, true);
                ImageReadParam param = reader.getDefaultReadParam();

                BufferedImage image = reader.read(0, param);
            //got an image file

                BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
            //bufferedImage is the RenderedImage to be written

                Graphics2D g2 = bufferedImage.createGraphics();
                g2.drawImage(image, null, null);

                File imageFile = new File("D:\\newrose2.jpg");
                ImageIO.write(bufferedImage, "jpg", imageFile);

例外:

javax.imageio.IIOException: Invalid JPEG file structure: SOS before SOF
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.readImageHeader(Native Method)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.readNativeHeader(JPEGImageReader.java:550)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.readNativeHeader(JPEGImageReader.java:550)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.checkTablesOnly(JPEGImageReader.java:295)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.gotoImage(JPEGImageReader.java:427)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.readHeader(JPEGImageReader.java:543)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:986)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:966)
    at Trnsport.writejpegfile(Trnsport.java:398)
    at Trnsport.getData(Trnsport.java:107)
    at Trnsport.run(Trnsport.java:63)
    at java.lang.Thread.run(Thread.java:722)

编辑:

FileOutputStream fos = new FileOutputStream("image" + new Date().getTime() + ".jpg");
fos.write(someByteArray);
    fos.close();

1 个答案:

答案 0 :(得分:1)

如果您的字节数组已包含有效的JPEG数据,则无需调用JPEG阅读器或编写器 - 您可以使用普通文件I / O将字节写入文件。

如果字节数组实际上包含某种格式的原始像素数据,则需要直接将其加载到BufferedImage中(例如通过setRGB)并将其编码为JPEG。

您尝试解码时遇到异常的事实意味着它不是JPEG数据,而是原始像素数据。或者,也许它完全是一种不同类型的图像,或者它有一个偏移到数组中的图像而不是数组的开始,或者它根本不是图像。