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

Migrating from JDK 1.5.0_06 to 1.8.0_66 - Replacing the deprecated Java JPEG classes

我目前正在将应用程序从 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();
}

您的代码中有问题的行是:

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

根本不需要这种转换和使用特定子class (JPEGImageWriter)。不依赖特定的插件 subclasses 也是一个好习惯。在这种情况下,只需使用 ImageWriter 基础 class.

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

其他一切都会正常工作,运行 和以前一样。

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