How to automatically crop the white border of an image in Java?

What is the easiest way to automatically crop a picture with a white border in Java? Thank you in advance

Solution

If you want to make the white part invisible, the best way is to use the image filter to make the white pixels transparent. Some good samples provided by @ philho are discussed here,

private Image getCroppedImage(String address) throws IOException{
    BufferedImage source = ImageIO.read(new File(address)) ;

    boolean flag = false ;
    int upperBorder = -1 ; 
    do{
        upperBorder ++ ;
        for (int c1 =0 ; c1 < source.getWidth() ; c1++){
            if(source.getRGB(c1,upperBorder) != Color.white.getRGB() ){
                flag = true;
                break ;
            }
        }

        if (upperBorder >= source.getHeight())
            flag = true ;
    }while(!flag) ;

    BufferedImage destination = new BufferedImage(source.getWidth(),source.getHeight() - upperBorder,BufferedImage.TYPE_INT_ARGB) ;
    destination.getGraphics().drawImage(source,upperBorder*-1,null) ;

    return destination ;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>