How to auto crop an image white border in Java?

前端 未结 4 969
北荒
北荒 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:31

    Here's a way to crop all 4 sides, using the color from the very top-left pixel as the baseline, and allow for a tolerance of color variation so that noise in the image won't make the crop useless

    public BufferedImage getCroppedImage(BufferedImage source, double tolerance) {
       // Get our top-left pixel color as our "baseline" for cropping
       int baseColor = source.getRGB(0, 0);
    
       int width = source.getWidth();
       int height = source.getHeight();
    
       int topY = Integer.MAX_VALUE, topX = Integer.MAX_VALUE;
       int bottomY = -1, bottomX = -1;
       for(int y=0; y bottomX) bottomX = x;
                if (y > bottomY) bottomY = y;
             }
          }
       }
    
       BufferedImage destination = new BufferedImage( (bottomX-topX+1), 
                     (bottomY-topY+1), BufferedImage.TYPE_INT_ARGB);
    
       destination.getGraphics().drawImage(source, 0, 0, 
                   destination.getWidth(), destination.getHeight(), 
                   topX, topY, bottomX, bottomY, null);
    
       return destination;
    }
    
    private boolean colorWithinTolerance(int a, int b, double tolerance) {
        int aAlpha  = (int)((a & 0xFF000000) >>> 24);   // Alpha level
        int aRed    = (int)((a & 0x00FF0000) >>> 16);   // Red level
        int aGreen  = (int)((a & 0x0000FF00) >>> 8);    // Green level
        int aBlue   = (int)(a & 0x000000FF);            // Blue level
    
        int bAlpha  = (int)((b & 0xFF000000) >>> 24);   // Alpha level
        int bRed    = (int)((b & 0x00FF0000) >>> 16);   // Red level
        int bGreen  = (int)((b & 0x0000FF00) >>> 8);    // Green level
        int bBlue   = (int)(b & 0x000000FF);            // Blue level
    
        double distance = Math.sqrt((aAlpha-bAlpha)*(aAlpha-bAlpha) +
                                    (aRed-bRed)*(aRed-bRed) +
                                    (aGreen-bGreen)*(aGreen-bGreen) +
                                    (aBlue-bBlue)*(aBlue-bBlue));
    
        // 510.0 is the maximum distance between two colors 
        // (0,0,0,0 -> 255,255,255,255)
        double percentAway = distance / 510.0d;     
    
        return (percentAway > tolerance);
    }
    

提交回复
热议问题