該程序應該採取截圖(haystack),然後在屏幕截圖中查找子圖像(針)。然後輸出針的位置。它使用for循環遍歷每個維度。它從左→右→上→下。在第36和37行中,從getSubImage()方法中引發了RasterFormatException。getSubImage()觸發器RasterFormatException
import java.awt.AWTException;
import java.awt.HeadlessException;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Test {
public static void main(String[] args) throws HeadlessException, AWTException, IOException, ClassNotFoundException {
BufferedImage haystack = new Robot().createScreenCapture(new Rectangle(
Toolkit.getDefaultToolkit().getScreenSize()));
Point p = findNeedle (ImageIO.read(new File ("needle.png")));
System.out.println(p.getX() + ", " + p.getY());
}
static Point findNeedle(BufferedImage needle) throws HeadlessException, AWTException {
BufferedImage haystack = new Robot().createScreenCapture(new Rectangle(
Toolkit.getDefaultToolkit().getScreenSize()));
for (int i = 0; i < haystack.getHeight(); i++) {
for (int j = 0; j < haystack.getWidth(); j++) {
if (haystack.getSubimage(j, i, haystack.getWidth() - needle.getWidth(),
haystack.getHeight() - needle.getHeight()) == needle) {
return new Point(j, i);
}
}
}
return null;
}
}
這是錯誤。
Exception in thread "main" java.awt.image.RasterFormatException: (x + width) is outside raster
at sun.awt.image.IntegerInterleavedRaster.createWritableChild(IntegerInterleavedRaster.java:467)
at java.awt.image.BufferedImage.getSubimage(BufferedImage.java:1173)
at test.Test.findNeedle(Test.java:36)
at test.Test.main(Test.java:20)"
「是否在柵格之外」不解釋什麼? – davidbuzatto 2012-07-23 21:21:05
堆棧跟蹤說'test.Test.findSpectators()',但我沒有看到它在你的代碼(或方法)中被調用。 – 2012-07-23 21:21:12
@JonLin謝謝。我修好了。 – Nyx 2012-07-23 21:22:46