canvas教程

Java屏幕截图工具 捕获屏幕

字号+ 作者:H5之家 来源:H5之家 2017-07-21 15:01 我要评论( )

原文:http://www.open-open.com/code/view/1420037709781 ...

import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.WindowConstants; /** * 捕获屏幕,屏幕截图工具 ScreenCaptureFrame extends JFrame implements ActionListener { PaintCanvas canvas = ScreenCaptureFrame() { super("Screen Capture"); init(); } /** * 初始化 init() { scrCaptureUtil = new ScreenCaptureUtil();// 创建抓屏工具 canvas = new PaintCanvas(scrCaptureUtil);// 创建画布 Container c = this.getContentPane(); c.setLayout(new BorderLayout()); c.add(canvas, BorderLayout.CENTER); JButton capButton = new JButton("抓 屏"); c.add(capButton, BorderLayout.SOUTH); capButton.addActionListener(this); this.setSize(400, 400); this.setVisible(true); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } canvas.drawScreen(); } main(String[] args) { new ScreenCaptureFrame(); } } /** * 抓屏工具类 */ class ScreenCaptureUtil { Rectangle scrRect = ScreenCaptureUtil() { try { robot = new Robot();// 创建一个抓屏工具 } catch (Exception ex) { System.out.println(ex.toString()); } // 获取屏幕的矩形图像 Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize(); scrRect = new Rectangle(0, 0, scrSize.width, scrSize.height); } /** * 抓屏方法 * * @return 返回一个图像 */ public BufferedImage captureScreen() { BufferedImage scrImg = null; try { scrImg = robot.createScreenCapture(scrRect);// 抓的是全屏图 } catch (Exception e) { System.out.println(e.toString()); } return scrImg; } } /** * 画布类,用于显示抓屏得到的图像 */ class PaintCanvas extends JPanel { BufferedImage scrImg = PaintCanvas(ScreenCaptureUtil screenUtil) { this.scrCaptureUtil = screenUtil; } /** * 重载JPanel的paintComponent,用于画背景 paintComponent(Graphics g) { if (scrImg != null) { int iWidth = this.getWidth(); int iHeight = this.getHeight(); g.drawImage(scrImg, 0, 0, iWidth, iHeight, 0, 0, scrImg.getWidth(), scrImg.getHeight(), null); } } /** * 画屏幕图像的方法 drawScreen() { Graphics g = this.getGraphics(); scrImg = scrCaptureUtil.captureScreen();(scrImg != null) { this.paintComponent(g);// 画图 } g.dispose();// 释放资源 } }

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • HTML5(Canvas Vedio Audio 拖动)

    HTML5(Canvas Vedio Audio 拖动)

    2017-07-18 13:14

  • HTML5 Canvas八大核心技术及其API用法

    HTML5 Canvas八大核心技术及其API用法

    2017-07-18 12:00

  • SurfaceView源码以及崩溃剖析

    SurfaceView源码以及崩溃剖析

    2017-07-14 16:01

  • android非硬件加速绘制简单流程

    android非硬件加速绘制简单流程

    2017-07-08 14:00

网友点评