[英]Capture a screenshot and convert it into a base64 String
Purpose of publishing this question is to help the armature coders and all to get out of the following problems (I found some misleading answers from the internet for the bellow problems) 发布此问题的目的是帮助电枢编码器以及所有人员摆脱以下问题(我从网上发现了一些关于以下问题的误导性答案)
Answer code is published by my self and guarantee the for 100% working state 答案代码由我自己发布,并保证100%的工作状态
In my opinion no need to create BufferedImage
keep it simply like : 在我看来,无需创建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;
}
Here is the answer 这是答案
Your need the following java imports 您需要以下java导入
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
and the method as follow 以及方法如下
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.