JPEG轉換成TIFF

項目背景

在項目中對於文檔的操作,一個重要的功能是文件類型的轉換,其中最重要的一個就使JPG轉TIF,之前在做該功能時,發現相關資料很少,參考了很多資料,完成了本功能。

功能條件

		<dependency>
            <groupId>ome</groupId>
            <artifactId>jai_imageio</artifactId>
            <version>5.5.3</version>
        </dependency>
        <dependency>
            <groupId>javax.media</groupId>
            <artifactId>jai_codec</artifactId>
            <version>1.1.3</version>
        </dependency>

        <dependency>
            <groupId>javax.media</groupId>
            <artifactId>jai_core</artifactId>
            <version>1.1.3</version>
        </dependency>

代碼

private String jpeg2Tiff(String fileName) throws Exception {
        String targetFile = fileName;
        if (targetFile.indexOf(".jpg") > 0) {
            targetFile = targetFile.replace(".jpg", ".tiff");
        } else if (fileName.indexOf(".JPG") > 0) {
            targetFile = targetFile.replace(".JPG", ".tiff");
        } else if (targetFile.indexOf(".jpeg") > 0) {
            targetFile = targetFile.replace(".jpg", ".tiff");
        } else if (fileName.indexOf(".JPEG") > 0) {
            targetFile = targetFile.replace(".JPEG", ".tiff");
        } else {
            targetFile = UUID.randomUUID().toString() + ".tiff";
        }
        if (new File(fileName).exists()) {
            String randomName = UUID.randomUUID().toString().replace("-", "");
            randomName = randomName.substring(randomName.length() - 9, randomName.length() - 1);
            targetFile = targetFile.replace(".tiff", randomName + ".tiff");
        }
        File jpegFile = new File(fileName);
        FileSeekableStream imageInputStream = new FileSeekableStream(jpegFile);
        PlanarImage inputImage = JAI.create("stream", imageInputStream);

        OutputStream outputStream = new FileOutputStream(targetFile);
        TIFFEncodeParam tiffParam = new TIFFEncodeParam();
        TIFFField[] extras = new TIFFField[2];
        extras[0] = new TIFFField(282, TIFFTag.TIFF_RATIONAL, 1, (Object) new long[][] { { (long) 200, 1 }, { 0, 0 } });
        extras[1] = new TIFFField(283, TIFFTag.TIFF_RATIONAL, 1, (Object) new long[][] { { (long) 200, 1 }, { 0, 0 } });
        tiffParam.setExtraFields(extras);
        tiffParam.setCompression(TIFFEncodeParam.COMPRESSION_JPEG_TTN2);
        // we can adjust jpeg quality here, default quality 0.75f
        JPEGEncodeParam jpegEncodeParam = tiffParam.getJPEGEncodeParam();
        jpegEncodeParam.setQuality(0.75f);
        tiffParam.setJPEGEncodeParam(jpegEncodeParam);
        ImageEncoder enc = ImageCodec.createImageEncoder("TIFF", outputStream, tiffParam);
        enc.encode(inputImage);
        outputStream.flush();
        outputStream.close();
        imageInputStream.close();
        return targetFile;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章