Search code examples
javaimageimage-processingbufferedimagejava-17

Image To Stencil in Java


I am new to image processing in java and I am trying to convert an image to stencil (I think stencil is name given for it!).

The input image is this:-

enter image description here

After processing the image would be like this:-

enter image description here

I searched google. But could find a solution. (maybe because I don't know what is the actual name of this process.)

Is this possible with java?


Solution

  • Yes I found the solution. if we Binarize an image it will work.

    Input image:-

    enter image description here

    Output Image:-

    enter image description here

    Code:-

    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    
    public class Main {
    
     
        public static void main(String[] args) throws  IOException {
            
            BufferedImage bi = ImageIO.read(new File("D:\\IMG_20211029_124954.jpg"));
            
          ImageIO.write(binarizeImage(bi), "png", new File("D:\\1.png"));
     
    }
    public static BufferedImage binarizeImage(BufferedImage img_param) 
    {
        BufferedImage image = new BufferedImage(
            img_param.getWidth(), 
            img_param.getHeight(),                                    
            BufferedImage.TYPE_BYTE_BINARY
        );
    
        Graphics g = image.getGraphics();
        g.drawImage(img_param, 0, 0, null);
        g.dispose();
    
        
        return image;
    }
    }
    

    To make the image transparent , You can do something like this:-

    for(int i=0;i<img.width;i++){
    for(int j=0;j<img.height;j++){
    Color c = new Color(255,255,255,0);
    if(img.getRGB==Color.white.getRGB){
    img.setRGB(i,j,c.getRGB)
    }
    }
    }