png 文件压缩为 jpeg 时变成全黑。是因为PNG是无损的吗?

发布于 2024-10-22 10:39:28 字数 1149 浏览 2 评论 0原文

我有一段代码,可以以一定的质量压缩jpg图像,但是当图像是png类型时,它们都变成黑色。知道为什么以及如何解决它吗?这是我的代码。

public void compressImage(String filename, ServletContext servletContext) {
    //You first need to enumerate the image writers that are available to jpg
    Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
    //Then, choose the first image writer available
    ImageWriter writer = (ImageWriter) iter.next();
    //instantiate an ImageWriteParam object with default compression options
    ImageWriteParam iwp = writer.getDefaultWriteParam();
    //Set the compression quality
    iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    iwp.setCompressionQuality(0.5f);
    try {
        BufferedImage img = ImageIO.read(new File(filename));
        String destPath = "/Users/KingdomHeart/resources/scholar/compress/compress.jpg";
        File file = new File(destPath);
        FileImageOutputStream output = new FileImageOutputStream(file);
        writer.setOutput(output);
        IIOImage image = new IIOImage(img, null, null);
        writer.write(null, image, iwp);
        writer.dispose();
    }catch(IOException e){

    }
}

I have a piece of code that compress an jpg image with a certain quality, but when the image is png type, they all turn black. Any idea why and how to fix it? here is my code.

public void compressImage(String filename, ServletContext servletContext) {
    //You first need to enumerate the image writers that are available to jpg
    Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
    //Then, choose the first image writer available
    ImageWriter writer = (ImageWriter) iter.next();
    //instantiate an ImageWriteParam object with default compression options
    ImageWriteParam iwp = writer.getDefaultWriteParam();
    //Set the compression quality
    iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    iwp.setCompressionQuality(0.5f);
    try {
        BufferedImage img = ImageIO.read(new File(filename));
        String destPath = "/Users/KingdomHeart/resources/scholar/compress/compress.jpg";
        File file = new File(destPath);
        FileImageOutputStream output = new FileImageOutputStream(file);
        writer.setOutput(output);
        IIOImage image = new IIOImage(img, null, null);
        writer.write(null, image, iwp);
        writer.dispose();
    }catch(IOException e){

    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡淡的优雅 2024-10-29 10:39:28

这可能有您正在寻找的答案:转换透明 gif / png使用 java 转换为 jpeg

问题可能是您正在使用具有一定透明度的 PNG。

This might have the answers you're looking for: Converting transparent gif / png to jpeg using java

The issue is likely that you're working with a PNG that has some transparency in it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文