我一直在尝试使用 rococoa(java 到 osx cocoa api 库)编写一个简单的屏幕截图应用程序,并设法实际拍摄屏幕截图,然后将其保存到文件中。不幸的是,有时,应用程序会因“位置的内存访问无效...”错误而失败。我假设这是由于某些东西被垃圾收集,因为我无法保持引用活着。导致崩溃的行是: int[] data = pointer.getIntArray(0, bytesPerPlane / 4);
我真的没有用Objective C编写任何东西,只是从rococoa开始,所以我发现自己对此感到困惑。我已经复制了下面的相关代码,非常感谢任何帮助!
public interface QuartzLibrary extends Library {
QuartzLibrary INSTANCE = (QuartzLibrary) Native.loadLibrary("Quartz", QuartzLibrary.class);
class CGPoint extends Structure {
public double x;
public double y;
}
class CGSize extends Structure {
public double width;
public double height;
}
class CGRect extends Structure implements Structure.ByValue {
public static class CGRectByValue extends CGRect { }
public CGPoint origin;
public CGSize size;
}
int kCGWindowListOptionIncludingWindow = (1 << 3);
int kCGWindowImageBoundsIgnoreFraming = (1 << 0);
ID CGWindowListCreateImage(CGRect screenBounds, int windowOption, int windowId, int imageOption);
}
public interface NSBitmapImageRep extends NSObject {
public static final _Class CLASS = Rococoa.createClass("NSBitmapImageRep", _Class.class);
public interface _Class extends NSClass {
NSBitmapImageRep alloc();
}
NSBitmapImageRep initWithCGImage(ID imageRef);
com.sun.jna.Pointer bitmapData();
NSSize size();
}
public class Screenshot {
public static void getScreenshot(int windowId) throws IOException {
QuartzLibrary.CGRect bounds = new QuartzLibrary.CGRect.CGRectByValue();
bounds.origin = new QuartzLibrary.CGPoint();
bounds.origin.x = 0;
bounds.origin.y = 0;
bounds.size = new QuartzLibrary.CGSize();
bounds.size.width = 0;
bounds.size.height = 0;
ID imageRef = QuartzLibrary.INSTANCE.CGWindowListCreateImage(bounds, QuartzLibrary.kCGWindowListOptionIncludingWindow, windowId, QuartzLibrary.kCGWindowImageBoundsIgnoreFraming);
NSBitmapImageRep imageRep = NSBitmapImageRep.CLASS.alloc();
imageRep = imageRep.initWithCGImage(imageRef);
NSSize size = imageRep.size();
com.sun.jna.Pointer pointer = imageRep.bitmapData();
int width = size.width.intValue();
int height = size.height.intValue();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
// The crash always happens when calling 'getIntArray' in the next line.
int[] data = pointer.getIntArray(0, bytesPerPlane / 4);
int idx = 0;
for(int y = 0; y < height; y++)
for(int x = 0; x < width; x++)
image.setRGB(x, y, data[idx++]);
ImageIO.write(image, "png", new File("foo.png"));
}
}