【问题标题】:Cutting shapes from image从图像中切割形状
【发布时间】:2015-10-02 19:42:40
【问题描述】:

我有一个缓冲图像和一组形状,如拼图。我想从图像中剪下这些形状。我尝试剪切图像,但它不能正常工作。到目前为止我所做的是:

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            Area area = areas[i][j];
            int width = (int) area.getBounds2D().getWidth();
            int height = (int) area.getBounds2D().getHeight();

            pieces[i][j] = new BufferedImage(width, height, image.getType());
            Graphics2D gr = pieces[i][j].createGraphics();
            gr.setClip(area);
            gr.drawImage(image, 0, 0, null);
            gr.dispose();

            try {
                ImageIO.write(pieces[i][j], "png", new File("img/img" + i + "" + j + ".png"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

它只适用于第一个形状,然后将透明图像写入输出。

【问题讨论】:

  • 您是否检查了 Area 对象与图像边界的交集是否为空? (也就是说,形状在图像上方,而不是其他地方或空的)
  • 我认为这将有助于我们更好地理解这个问题,如果你显示你想要剪辑的图像,并打印几个Areas。您只是想像@Glains 认为的那样提取子图像,还是真的想像@lbalazscs 认为的那样将单个图像剪辑成多个形状? :-)
  • 绝对有必要在问题中添加至少一些形状的细节。第一个成功的形状,还有几个没有成功的形状。包括创建形状的数据以及 i 和 j 的数据。

标签: java graphics bufferedimage java-2d clipping


【解决方案1】:

实际上有很多方法可以做到这一点。这是我的方法:)

int width = 0;
int height = 0;
int rows = 0;
int columns = 0;
BufferedImage sheet = // you image goes here 
BufferedImage[] pieces = new BufferedImage[rows * cols];
for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        pieces[(i * cols) + j] = sheet.getSubimage(j * width, i * height, width, height);    
    }
}

请注意,这些片段都在一个数组中。如果您仍然希望您的作品在二维数组中:

// Switch these lines
BufferedImage[][] pieces = new BufferedImage[rows][cols];
pieces[i][j] = sheet.getSubimage(j * width, i * height, width, height);   

补充阅读: Spritesheets 和动画
点击here!

【讨论】:

  • 如果您想使用动态方法来计算 1 件的宽度和高度,只需调用 int width = sheet.getWidth() / colums;,但您必须将工作表声明放在计算的顶部才能完成这项工作。
  • 在我看来,这个答案错过了 OP 的重点,他(据我所知)想要剪出非矩形形状
  • 我从问题文本中理解了其他内容,但如果这不是确切的答案,我很抱歉。对于更详细的问题,我需要一个更清晰的问题,并最终给出给定的图像和首选结果。 (拼图通常是正方形,所以应该可以)
猜你喜欢
  • 2011-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
  • 1970-01-01
  • 2013-08-08
  • 2016-08-17
  • 1970-01-01
相关资源
最近更新 更多