将PNG转换为TIFF-Java时出错

时间:2013-08-08 07:09:58

标签: java png tiff javax.imageio jai

我正在处理以下片段,该片段应该将我的png文件转换为tiff。

            String fileName = "4848970_1";
            // String fileName = "color";
            String inFileType = ".PNG";
            String outFileType = ".TIFF";

            File fInputFile = new File("C:\\Users\\abc\\Downloads\\image2.png");
            InputStream fis = new BufferedInputStream(new FileInputStream(fInputFile));
            ImageReaderSpi spi = new PNMImageReaderSpi();
            ImageReader reader = spi.createReaderInstance();
            ImageInputStream iis = ImageIO.createImageInputStream(fis);
            reader.setInput(iis, true);
            BufferedImage bi = reader.read(0);

            int[] xi = bi.getSampleModel().getSampleSize();

            for (int i : xi) {
                System.out.println("bitsize " + i);
            }

            ImageWriterSpi tiffspi = new TIFFImageWriterSpi();
            TIFFImageWriter writer = (TIFFImageWriter) tiffspi.createWriterInstance();

            // TIFFImageWriteParam param = (TIFFImageWriteParam) writer.getDefaultWriteParam();
            TIFFImageWriteParam param = new TIFFImageWriteParam(Locale.US);
            String[] strings = param.getCompressionTypes();
            for (String string : strings) {
                System.out.println(string);
            }

            //param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            //param.setCompressionType("LZW");

            File fOutputFile = new File("C:\\Users\\abc\\Downloads\\" + fileName + outFileType);
            OutputStream fos = new BufferedOutputStream(new FileOutputStream(fOutputFile));
            ImageOutputStream ios = ImageIO.createImageOutputStream(fos);

            writer.setOutput(ios);
            writer.write(null, new IIOImage(bi, null, null), param);

            ios.flush();
            writer.dispose();
            ios.close();

但是这给了我以下错误

Exception in thread "main" java.lang.RuntimeException: What in the stream isn't a PNM image.
    at com.sun.media.imageioimpl.plugins.pnm.PNMImageReader.readHeader(PNMImageReader.java:187)
    at com.sun.media.imageioimpl.plugins.pnm.PNMImageReader.read(PNMImageReader.java:301)
    at javax.imageio.ImageReader.read(Unknown Source)
    at com.imageconv.TiffImage.main(TiffImage.java:40)

它是否无法读取PNG文件或将其识别为非png文件。我在哪里错了?

1 个答案:

答案 0 :(得分:2)

您正在尝试将PNG图像读取为PNM图像。这两种文件格式没有任何共同之处;因此错误。