Search code examples
javaimage-processingjava-8bufferedimagegraphics2d

Convert color image into black and white using java created from scratch


I want to convert my picture from colored to Black and white which seems to be created from scratch. Here is the code which i tried as described on the different post:

    BufferedImage bi = ImageIO.read(new File("/Users/***/Documents/Photograph.jpg"));
    ColorConvertOp op = 
        new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
    ImageIO.write(bi, "PNG", new File("/Users/bng/Documents/rendered2.png"));
    op.filter(bi, bi);

But still my image is not converted to the Black and white. Additionally, this code is increasing the rendered2.png image size to 10 folds. Also, it would be great if i could find some Java 8 way of doing this. Any suggestions?


Solution

    1. You have to find RGB of the existing colors of the image you want to change it.
    2. Fyi, you want to change it as white RGB value is (255,255,255) and for black RGB value is (0,0,0)

    3. Following method easily do the color change if you apply correct way of your requirement

      private BufferedImage changeColor(BufferedImage image, int srcColor, int replaceColor)
      {
          BufferedImage destImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
          Graphics2D g = destImage.createGraphics();
          g.drawImage(image, null, 0, 0);
          g.dispose();
      
      
          for (int width = 0; width < image.getWidth(); width++)
          {
              for (int height = 0; height < image.getHeight(); height++)
              {
      
                 if (destImage.getRGB(width, height) == srcColor)
                  {
                     destImage.setRGB(width, height, replaceColor);
                  }
      
              }
          }
      
          return destImage;
      }