!596 // auto-import import javax.imageio.*; import java.awt.image.*; import java.awt.*; public class main { public static void main(String[] args) throws Exception { BufferedImage image = makeScreenshot(); save("output/screenshot.png", image); } static void save(String path, BufferedImage image) throws IOException { saveBinaryFile(path, convertToPNG(image)); } public static BufferedImage makeScreenshot() { try { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Rectangle screenRectangle = new Rectangle(screenSize); Robot robot = new Robot(); return robot.createScreenCapture(screenRectangle); } catch (Exception e) { throw new RuntimeException(e); } } public static byte[] convertToPNG(BufferedImage image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(image, "png", baos); } catch (IOException e) { throw new RuntimeException(e); } return baos.toByteArray(); } /** writes safely (to temp file, then rename) */ public static void saveBinaryFile(String fileName, byte[] contents) throws IOException { File file = new File(fileName); File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); String tempFileName = fileName + "_temp"; FileOutputStream fileOutputStream = new FileOutputStream(tempFileName); fileOutputStream.write(contents); fileOutputStream.close(); if (file.exists() && !file.delete()) throw new IOException("Can't delete " + fileName); if (!new File(tempFileName).renameTo(file)) throw new IOException("Can't rename " + tempFileName + " to " + fileName); } }