Как мы можем удалить белый неиспользуемый фон из изображения с помощью Java? [Дубликат]

Это работает, если вам нужен только общий файл с простым URL-адресом. Обратите внимание, что это может привести к отмене ваших правил хранения Firebase.

bucket.upload(file, function(err, file) {
    if (!err) {
      //Make the file public
      file.acl.add({
      entity: 'allUsers',
      role: gcs.acl.READER_ROLE
      }, function(err, aclObject) {
          if (!err) {
              var URL = "https://storage.googleapis.com/[your bucket name]/" + file.id;
              console.log(URL);
          } else {
              console.log("Failed to set permissions: " + err);
          }
      });  
    } else {
        console.log("Upload failed: " + err);
    }
});
9
задан rreyes1979 21 May 2012 в 00:16
поделиться

3 ответа

Если вы хотите, чтобы белые части были невидимыми, лучший способ - использовать фильтры изображений и сделать белые пиксели прозрачными, здесь обсуждается здесь с помощью @PhiLho с некоторыми хорошими образцами, если вы хотите изменить размер ваше изображение так, чтобы границы не имели белых цветов, вы можете сделать это с четырьмя простыми циклами, этот маленький метод, который я написал для вас, делает трюк, обратите внимание, что он просто обрезает верхнюю часть изображения, вы можете написать остальные ,

    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 ;
}
5
ответ дан Community 26 August 2018 в 19:10
поделиться

Вот способ обрезать все 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);
}
23
ответ дан Todd 26 August 2018 в 19:10
поделиться

И вот еще один пример

private static BufferedImage autoCrop(BufferedImage sourceImage) {
    int left = 0;
    int right = 0;
    int top = 0;
    int bottom = 0;
    boolean firstFind = true;
    for (int x = 0; x < sourceImage.getWidth(); x++) {
        for (int y = 0; y < sourceImage.getWidth(); y++) {
            // pixel is not empty
            if (sourceImage.getRGB(x, y) != 0) {

                // we walk from left to right, thus x can be applied as left on first finding
                if (firstFind) {
                    left = x;
                }

                // update right on each finding, because x can grow only
                right = x;

                // on first find apply y as top
                if (firstFind) {
                    top = y;
                } else {
                    // on each further find apply y to top only if a lower has been found
                    top = Math.min(top, y);
                }

                // on first find apply y as bottom
                if (bottom == 0) {
                    bottom = y;
                } else {
                    // on each further find apply y to bottom only if a higher has been found
                    bottom = Math.max(bottom, y);
                }
                firstFind = false;
            }
        }
    }

    return sourceImage.getSubimage(left, top, right - left, bottom - top);
}
0
ответ дан wutzebaer 26 August 2018 в 19:10
поделиться
Другие вопросы по тегам:

Похожие вопросы: