简体   繁体   中英

RGBImageFilter not affecting my image

I am trying to change the colors in a .png-file using RGBImageFilter and FilteredImageSource and then save the file to disk, and it seems to be working fine.. but when I open the new file after the program has finished, it looks just like the original, ie I have just copied the file.

The codes looks like this:

public class ChangeImageColor {

    public static void main(String[] args) {    
        BufferedImage image = null;
        try {
            image = ImageIO.read(new File("png_test.png") );                
            ImageFilter colorfilter = new RedBlueSwapFilter();              
            FilteredImageSource filteredImageSource = new FilteredImageSource(image.getSource(), colorfilter );             
            Image filteredImage = Toolkit.getDefaultToolkit().createImage(filteredImageSource);             
            BufferedImage filtered = new BufferedImage(
                    filteredImage.getWidth(null), filteredImage.getHeight(null),
                    BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2 = filtered.createGraphics();
            g2.drawImage(image, 0, 0, null);
            g2.dispose();           
            save(filtered, "png");    
        } catch( IOException e){
            //do something
            System.out.print(e.getMessage());
        }
    }

    private static void save(BufferedImage image, String ext) {
        String fileName = "png_test_manipulated";
        File file = new File(fileName + "." + ext);
        try {
            ImageIO.write(image, ext, file);  // ignore returned boolean
        } catch(IOException e) {
            System.out.println("Write error for " + file.getPath() +
                               ": " + e.getMessage());
        }
    }       

    static class RedBlueSwapFilter extends RGBImageFilter {
        public RedBlueSwapFilter() {
            // The filter's operation does not depend on the
            // pixel's location, so IndexColorModels can be
            // filtered directly.
            canFilterIndexColorModel = true;
        }

        @Override
        public int filterRGB(int x, int y, int rgb) {    
            /*return ((rgb & 0xff00ff00)
                    | ((rgb & 0xff0000) >> 16)
                    | ((rgb & 0xff) << 16));*/
            return 0x00000000;
        }
    }    
}

your problem:

   g2.drawImage(image, 0, 0, null);

you draw the old image with this code, try to remove this lines:

   Graphics2D g2 = filtered.createGraphics();
   g2.drawImage(image, 0, 0, null);
   g2.dispose();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM