How to auto crop an image white border in Java?

前端 未结 4 972
北荒
北荒 2020-12-15 11:04

What\'s the easiest way to auto crop the white border out of an image in java? Thanks in advance...

4条回答
  •  情书的邮戳
    2020-12-15 11:42

    If you want the white parts to be invisible, best way is to use image filters and make white pixels transparent, it is discussed here by @PhiLho with some good samples, if you want to resize your image so it's borders won't have white colors, you can do it with four simple loops, this little method that I've write for you does the trick, note that it just crop upper part of image, you can write the rest,

        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, 0, upperBorder*-1, null) ;
    
        return destination ;
    }
    

提交回复
热议问题