java - 压缩JPG使图像变绿

标签 java compression jpeg javax.imageio image-compression

当我尝试压缩 jpg 图像时,大多数情况下效果很好,但有些 jpg 图像在压缩后变绿了。这是我的代码

public void compressImage(String filename, String fileExtension) {
    BufferedImage img = null;
    try {
        File file = new File(filename);
        img = ImageIO.read(file);

        if (fileExtension.toLowerCase().equals(".png") || fileExtension.toLowerCase().equals(".gif")) {
            //Since there might be transparent pixel, if I dont do this,
            //the image will be all black.
            for (int x = 0; x < img.getWidth(); x++) {
                for (int y = 0; y < img.getHeight(); y++) {
                    int rgb = img.getRGB(x, y);
                    int alpha = (rgb >> 24) & 0xff;
                    if (alpha != 255) {
                        img.setRGB(x, y, -1); //set white
                    }
                }
            }
        }
        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.8f);
        //delete the file. If I dont the file size will stay the same
        file.delete();
        ImageOutputStream output = ImageIO.createImageOutputStream(new File(filename));
        writer.setOutput(output);
        IIOImage image = new IIOImage(img, null, null);
        writer.write(null, image, iwp);
        writer.dispose();
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, ioe.getMessage());
    }
}

Original Image Compress Image. Image turn green

最佳答案

将最终图像从 YUV 转换回 RGB,将恢复图像的颜色。 这种转换对我有用:cv2.cvtColor(img_file, cv2.COLOR_YUV2RGB)

关于java - 压缩JPG使图像变绿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5316295/

相关文章:

java - "import static class.*;"相对于多个静态 "class.method()"调用有何优势?

python - 霍夫曼编码树遍历

javascript - 使用 zip.js 压缩一个 Blob

java - 通信异常 : Communications link failure

java编译的类包含美元符号

java - 在Windows启动时执行Jar不起作用,没有结果

c++ - 类似 smartassembly 的程序,但适用于 C++?

c# - 使用 FreeImage 对 JPEG 进行无损优化

php - 存储的数据库网址不回显图像

linux - QTcreator + Cimg.h = 打开 .jpg .png 时出错