如何用Java提取此图像的一部分?

点击Upvote:

我有这个精灵表:

吃豆精灵

如何读取此图像文件以提取其一部分以用作精灵

酷鸟:

如果将精灵区域读取为BufferedImage,则该getSubimage方法可用于获取精灵表的子图像。

getSubimage方法将采取xy以及widthheight期望的子图像,从而能够得到所希望的子画面。由于大多数精灵的大小似乎相同,因此我认为可以通过嵌套for循环来检索大多数精灵,以遍历大图像。

例如,如果使用ImageIO类(例如read方法)加载子画面图像,并且每个子画面的大小为10像素乘10像素,其中5行乘5列子画面,则可以通过以下方式获得子画面:

BufferedImage bigImg = ImageIO.read(new File("sheet.png"));
// The above line throws an checked IOException which must be caught.

final int width = 10;
final int height = 10;
final int rows = 5;
final int cols = 5;
BufferedImage[] sprites = new BufferedImage[rows * cols];

for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < cols; j++)
    {
        sprites[(i * cols) + j] = bigImg.getSubimage(
            j * width,
            i * height,
            width,
            height
        );
    }
}

当然,要注意的是,以上代码仅在所有精灵大小相同的情况下才有效,因此需要进行一些调整才能对给定的精灵工作。(由于右上角的尺寸似乎与其他尺寸不同。)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章