0

I tried to modify the pixel value of the Green band of a Jpeg image by Java. Strangely, after I modified the green band, the values of the red and blue bands also changed. The same code to modify PNG is successfully. Does this have something to do with Jpeg being a lossy compression format? The code:

static void ModifyJPEG()
    {
        try {
            File file=new File("G:\\Data\\Md\\TestJPEG.jpg");
            File newfile=new File("G:\\Data\\Md\\TestJPEG2.jpg");
            BufferedImage bufferedImage= ImageIO.read(file);

            BufferedImage newbufferedImage= new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_3BYTE_BGR);

            for (int i = bufferedImage.getMinX(); i < bufferedImage.getWidth(); i++)
            {
                for (int j = bufferedImage.getMinY(); j < bufferedImage.getHeight(); j++)
                {
                    int rgb = bufferedImage.getRGB(i, j);
                    Color color=new Color(rgb);
                    int r=color.getRed();
                    int g=color.getGreen();
                    int b=color.getBlue();
                    int gchange=g/3;
                    Color newcolor=new Color(r,gchange,b); 
                    newbufferedImage.setRGB(i, j, newcolor.getRGB());
                }
            }
            
            ImageIO.write(newbufferedImage, "jpg",  newfile);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
YuChen
  • 1
  • 1
  • 2
    JPEG is not a lossless compression format, you probably meant PNG. The Reason why the other colors changed too is mostly because those colors are not independent from each other. Read the documentation about how JPEG works. – paladin Jan 26 '22 at 13:31
  • I think you meant to say that JPEG is a "lossy" compression (not a "lossless" one), and yes, that is most likely the cause. JPEG also suffers from something called "generational loss", so each time you re-compress the same values, the result will be "worse". If you want to use JPEG, you should also accept some slight variance in color values. – Harald K Jan 26 '22 at 14:24
  • Sry,the JPEG is a lossy compression format and I have modified. – YuChen Jan 26 '22 at 15:50

0 Answers0