如何从形状中减去图像的面积

时间:2017-02-15 12:05:44

标签: java graphics paint paintcomponent graphics2d

这里的基本问题是我绘制了一个灰度的图像,它是形状的矩形边界。我已在该矩形上绘制了形状。现在我需要从图像中删除访问区域。

从形状中获取矩形边界的代码是:

focusDiv

绘制矩形和所选形状的代码是:

public static Rectangle getBoundingBox(Shape shape,Graphics2D g) {
     int minX = Integer.MAX_VALUE;
     int minY = Integer.MAX_VALUE;
     int maxX = Integer.MIN_VALUE;
     int maxY = Integer.MIN_VALUE;

    final Rectangle polygonBounds = shape.getBounds();

    int ax = polygonBounds.x;
    int ay = polygonBounds.y;
    int bx = ax + polygonBounds.width;
    int by = ay + polygonBounds.height;

    minX = Math.min(ax, minX);
    minY = Math.min(ay, minY);
    maxX = Math.max(bx, maxX);
    maxY = Math.max(by, maxY);


final Rectangle boundingBox = new Rectangle(minX, minY, 1, 1);
boundingBox.add(maxX, maxY);
return boundingBox;
}    

灰度矩形内的图像的代码是:

        Rectangle rect = getBoundingBox((Shape)selectedArea,g);
        int x = (int)rect.getX();
        int y = (int)rect.getY();
        int width = (int)rect.getWidth();
        int height = (int)rect.getHeight();
        if((x+width)>grayScaledImage.getWidth()){
            width = grayScaledImage.getWidth()-x;
        }
        if(((y+height)>grayScaledImage.getHeight())){
            height = grayScaledImage.getHeight()-y;
        }

        BufferedImage img = grayScaledImage.getSubimage(x,y,width,height);
            }
            }
        }

        g.drawImage(img,x,y,null);

我已经尝试过使用setClip()方法,但它有一些抗锯齿问题。所以获得一些帮助会很棒。

图像是:

enter image description here

需要从图像中减去光线灰度级部分。

所需的图片是:

enter image description here

Polygon可以是任何形状。

2 个答案:

答案 0 :(得分:0)

我建议您尝试这种方式: 您可以创建Polygon对象并提供xPointsyPoint。像这样的东西

int[] xPoints;
int[] yPoints;
int length = xPoint.length;
Polygon polygon = new Polygon(xPoints, yPoints, length );

现在添加这样的颜色:

Rectangle bounds = polygon.getBounds();
for (int i = 0; i < bounds.width; i++) {
    for (int j = 0; j < bounds.height; j++) {
        if (polygon.contains(i, j)) {// check if the point is inside the polygon
            // do the color stuff here
            Color c = new Color(image.getRGB(j, i));
            int red = (int) (c.getRed() * 0.3);
            int green = (int) (c.getGreen() * 0.59);
            int blue = (int) (c.getBlue() * 0.11);

            int sum = red + green + blue;
            Color newColor = new Color(sum, sum, sum);
            //Color newColor =Color.red;
            image.setRGB(j, i, newColor.getRGB());
        }
    }
}

就是那个(没有任何额外的过程)

答案 1 :(得分:0)

代码中的一个小错误:索引在循环中被反转。 正确的版本是:

Color c = new Color(image.getRGB(i, j));
        int red = (int) (c.getRed() * 0.3);
        int green = (int) (c.getGreen() * 0.59);
        int blue = (int) (c.getBlue() * 0.11);

        int sum = red + green + blue;
        Color newColor = new Color(sum, sum, sum);
        //Color newColor =Color.red;
        image.setRGB(i, j, newColor.getRGB());