在 Windows 中使用 JNA(Java Native Access)进行截图,可以通过调用 Windows API 来实现。以下是一个详细的步骤和示例代码,展示如何使用 JNA 截图。
pom.xml
文件中添加 JNA 依赖:<dependency> <groupId>net.java.dev.jna</groupId> <artifactId>jna</artifactId> <version>5.8.0</version> </dependency> <dependency> <groupId>net.java.dev.jna</groupId> <artifactId>jna-platform</artifactId> <version>5.8.0</version> </dependency>以下是一个完整的示例代码,展示如何使用 JNA 截图:
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.GDI32;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinGDI;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.platform.win32.WinUser;
import com.sun.jna.ptr.PointerByReference;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class JNAScreenshot {
public static void main(String[] args) {
try {
BufferedImage screenshot = captureScreen();
ImageIO.write(screenshot, "png", new File("screenshot.png"));
System.out.println("Screenshot saved as screenshot.png");
} catch (IOException e) {
e.printStackTrace();
}
}
public static BufferedImage captureScreen() {
User32 user32 = User32.INSTANCE;
GDI32 gdi32 = GDI32.INSTANCE;
WinDef.HWND hwnd = user32.GetDesktopWindow();
WinDef.HDC hdcWindow = user32.GetDC(hwnd);
WinDef.HDC hdcMemDC = gdi32.CreateCompatibleDC(hdcWindow);
WinDef.RECT bounds = new WinDef.RECT();
user32.GetWindowRect(hwnd, bounds);
int width = bounds.right - bounds.left;
int height = bounds.bottom - bounds.top;
WinDef.HBITMAP hBitmap = gdi32.CreateCompatibleBitmap(hdcWindow, width, height);
WinNT.HANDLE hOld = gdi32.SelectObject(hdcMemDC, hBitmap);
gdi32.BitBlt(hdcMemDC, 0, 0, width, height, hdcWindow, 0, 0, WinGDI.SRCCOPY);
gdi32.SelectObject(hdcMemDC, hOld);
gdi32.DeleteDC(hdcMemDC);
user32.ReleaseDC(hwnd, hdcWindow);
BufferedImage image = getBufferedImageFromBitmap(hBitmap);
gdi32.DeleteObject(hBitmap);
return image;
}
private static BufferedImage getBufferedImageFromBitmap(WinDef.HBITMAP hBitmap) {
GDI32 gdi32 = GDI32.INSTANCE;
WinGDI.BITMAPINFO bmi = new WinGDI.BITMAPINFO();
bmi.bmiHeader.biSize = new WinDef.DWORD(bmi.bmiHeader.size());
bmi.bmiHeader.biWidth = 0;
bmi.bmiHeader.biHeight = 0;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = WinGDI.BI_RGB;
PointerByReference pBits = new PointerByReference();
gdi32.GetDIBits(null, hBitmap, 0, 0, null, bmi, WinGDI.DIB_RGB_COLORS);
bmi.bmiHeader.biHeight = -bmi.bmiHeader.biHeight; // Flip the image vertically
BufferedImage image = new BufferedImage(bmi.bmiHeader.biWidth, Math.abs(bmi.bmiHeader.biHeight), BufferedImage.TYPE_INT_RGB);
gdi32.GetDIBits(null, hBitmap, 0, image.getHeight(), image.getRaster().getDataBuffer(), bmi, WinGDI.DIB_RGB_COLORS);
return image;
}
}
User32
和 GDI32
接口来调用 Windows API 函数。BufferedImage
。BufferedImage
为图像文件。领取专属 10元无门槛券
手把手带您无忧上云