从JDK 1.5.0_06迁移到1.8.0_66 - 替换已弃用的Java JPEG类

时间:2016-01-21 09:01:01

标签: java java-8 jpeg javax.imageio

我目前正在将应用程序从JDK 1.5.0_06迁移到1.8.0_66。在应用程序中,有多个文件使用com.sun.image.codec.jpeg类。当我尝试创建JAR时,我收到以下错误。

error: package com.sun.image.codec.jpeg does not exist import com.sun.image.codec.jpeg.*;

我在Replacing the deprecated Java JPEG classes for Java 7上引用了博客,我的错误被清除了。但现在我收到以下警告:

warning: JPEGImageWriter is internal proprietary API and may be removed in a future release import com.sun.imageio.plugins.jpeg.JPEGImageWriter;

来自博客的有问题的代码:

public static void saveAsJPEG(String jpgFlag, BufferedImage image_to_save, float JPEGcompression, FileOutputStream fos) throws IOException {
    // Image writer
    JPEGImageWriter imageWriter = (JPEGImageWriter) ImageIO.getImageWritersBySuffix("jpeg").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
    imageWriter.setOutput(ios);

    //and metadata
    IIOMetadata imageMetaData = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(image_to_save), null);

    if (jpgFlag != null) {
        int dpi = 96;

        try {
            dpi = Integer.parseInt(jpgFlag);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        //new metadata
        Element tree = (Element) imageMetaData.getAsTree("javax_imageio_jpeg_image_1.0");
        Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
        jfif.setAttribute("Xdensity", Integer.toString(dpi));
        jfif.setAttribute("Ydensity", Integer.toString(dpi));
    }

    if (JPEGcompression >= 0 && JPEGcompression <= 1f) {
        // new Compression
        JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
        jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
        jpegParams.setCompressionQuality(JPEGcompression);
    }

    //new Write and clean up
    imageWriter.write(imageMetaData, new IIOImage(image_to_save, null, null), null);
    ios.close();
    imageWriter.dispose();
}

1 个答案:

答案 0 :(得分:4)

代码中有问题的行是:

JPEGImageWriter imageWriter = (JPEGImageWriter) ImageIO.getImageWritersBySuffix("jpeg").next();

根本不需要对特定子类(JPEGImageWriter)进行此转换和使用。不依赖于特定的插件子类也是一种很好的做法。在这种情况下,只需使用ImageWriter基类。

ImageWriter imageWriter = ImageIO.getImageWritersBySuffix("jpeg").next();

其他一切都会像以前一样运作和运行。

注意:另一方面,JPEGImageWriteParam是公共API javax.imageio.plugins.jpeg包)的一部分,需要访问JPEG特定的写入选项。这种用法完全没问题。