发布这个问题的目的是帮助电枢编码员和所有人摆脱以下问题(我发现互联网上有一些误导性问题的答案)
答案代码由我自己发布,并保证100%工作状态
答案 0 :(得分:0)
在我看来,不需要创建BufferedImage
就像保持它一样:
public String captureToBase64() {
Rectangle screenSize = new
Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage screenCapture = null;
String base64Encoded = "";
try {
screenCapture = new Robot().createScreenCapture(screenSize);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(screenCapture, "jpg", baos);
baos.flush();
byte[] encodeBase64 = Base64.encodeBase64(baos.toByteArray());
base64Encoded = new String(encodeBase64);
baos.close();
} catch (AWTException e) {
e.getMessage();
}
return base64Encoded;
}
答案 1 :(得分:-2)
以下是答案
您需要以下java导入
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
和方法如下
public final String takeScreenshot() {
String base64 = "";
try {
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture;
capture = new Robot().createScreenCapture(screenRect);
BufferedImage bufferedThumbnail = new BufferedImage(capture.getWidth(null), capture.getHeight(null),
BufferedImage.TYPE_INT_RGB);
bufferedThumbnail.getGraphics().drawImage(capture, 0, 0, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedThumbnail, "png", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
byte[] encodedArr = Base64.encodeBase64(imageInByte);
// base64 = encodedArr.toString();
base64 = new String(encodedArr);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error While Getting Screen Shot" + e.getLocalizedMessage());
}
return base64;
}