如何提取这一形象在Java中的一部分? [英] How to extract part of this image in Java?

查看:314
本文介绍了如何提取这一形象在Java中的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个精灵表:

我怎样才能读取这个映像文件中提取一部分用作一个精灵

How can I read this image file to extract part of it to be used as a sprite ?

推荐答案

如果精灵区读入<一个href="http://java.sun.com/javase/6/docs/api/java/awt/image/BufferedImage.html"><$c$c>BufferedImage,在<一个href="http://java.sun.com/javase/6/docs/api/java/awt/image/BufferedImage.html#getSubimage%28int,%20int,%20int,%20int%29"><$c$c>getSubimage方法可用于获取精灵表的一个子图像。

If the sprites area read into a BufferedImage, the getSubimage method can be used to get a subimage of the sprite sheet.

getSubimage 方法将取 X ,并能获得宽度高度所需的子图像,因此所需要的精灵。由于大部分的精灵似乎是相同的大小,我认为他们大多可以通过嵌套的循环检索到遍历大图片。

The getSubimage method will take the x, y, and the width and height of the desired subimage, so the desired sprite can be obtained. Since most of the sprites seem to be the same size, I would think most of them can be retrieved by a nested for loop to iterate through the large image.

例如,如果子画面图像是使用 的ImageIO 类(如<一个href="http://java.sun.com/javase/6/docs/api/javax/imageio/ImageIO.html#read%28java.io.File%29"><$c$c>read法),并且每个子画面是10象素×10像素的大小,其中有5行×精灵5列,精灵可通过以下获得:

For example, if the sprite image is loaded using the ImageIO class (such as the read method), and each sprite is 10 pixels by 10 pixels in size, where are 5 rows by 5 columns of sprites, the sprites can be obtained by the following:

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
        );
    }
}

美中不足的是,当然,如果所有的精灵都是一样的尺寸上code只会工作,因此将需要为了进行工作,为给定的精灵表进行一些调整。 (作为顶级右上角似乎是在与其他大小不同。)

The catch is, of course, the above code will only work if all the sprites are the same size, so there will need to be some adjustment performed in order to work for the given sprite sheet. (As the top right-hand corner seems to be different in size from the others.)

这篇关于如何提取这一形象在Java中的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆