当前位置:   article > 正文

在 Java 中自动裁剪图像的白色边框_java 裁剪白色像素

java 裁剪白色像素

在业务场景中是要在前端中用Javascript来实现这个功能,如果在后端实现也不是不可以,所以网上搜索了一番,但是最后没有尝试和采用这种方法(用了一种很low的方法),在此记录一下,日后再用到类似的可以翻出来看看。

裁剪所有 4 个边的方法,使用最左上角像素的颜色作为基线,并允许颜色变化的容差,这样图像中的噪声就不会使裁剪变得无用

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<height; y++) {
      for(int x=0; x<width; x++) {
         if (colorWithinTolerance(baseColor, source.getRGB(x, y), tolerance)) {
            if (x < topX) topX = x;
            if (y < topY) topY = y;
            if (x > 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);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

原文链接

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/604358
推荐阅读
相关标签
  

闽ICP备14008679号