Search code examples
javabase64encodescreen-captureawtrobot

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)

  • Capture a desktop Image by Java robot
  • Image convert/encode to the base64 String

Answer code is published by my self and guarantee the for 100% working state


Solution

  • In my opinion no need to create BufferedImage keep it simply like :

    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;
    }