Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

54
LINES

< > BotCompany Repo | #626 // Screenshot maker (JavaX)

JavaX source code - run with: x30.jar

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

Author comment

Seems to work. (java x12 626 yields an output/screenshot.png)

download  show line numbers  debug dex  old transpilations   

Travelled to 14 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, teubizvjbppd, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #626
Snippet name: Screenshot maker (JavaX)
Eternal ID of this version: #626/1
Text MD5: 6c33b128982e13c41054003b8f7b8b8e
Author: stefan
Category: javax
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-06-19 20:41:23
Source code size: 1775 bytes / 54 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 685 / 621
Referenced in: [show references]