捕获当前屏幕图像

捕获当前屏幕图像

need to be optimized. relate 使用JFreeChart创建图象
Java代码 复制代码 收藏代码
  1. import java.awt.*;
  2. import java.awt.image.*;
  3. import com.sun.image.codec.jpeg.*;
  4. class ImageCanvas extends Canvas{
  5. private Image image;
  6. private Dimension prefSize;
  7. public ImageCanvas(Image image){
  8. this.image = image;
  9. calculatePreferredSize();
  10. }
  11. public void setImage(Image image){
  12. this.image = image;
  13. calculatePreferredSize();
  14. repaint();
  15. }
  16. private void calculatePreferredSize(){
  17. prefSize = new Dimension(image.getWidth(this),image.getHeight(this));
  18. System.out.println(image.getWidth(this));
  19. setSize(prefSize);
  20. }
  21. public Dimension getPreferredSize() {
  22. return prefSize;
  23. }
  24. public Dimension getMinimumSize() {
  25. return prefSize;
  26. }
  27. public void update(Graphics g){
  28. paint(g);
  29. }
  30. public void paint(Graphics g){
  31. g.drawImage(image,0,0,null);
  32. }
  33. }
  34. class ImageUtils{
  35. public static Image getScreenImage(){
  36. Robot robot;
  37. try {
  38. robot = new Robot();
  39. }catch(Exception e) {
  40. throw new RuntimeException("unable to construct Robot");
  41. }
  42. Dimension screenDims =Toolkit.getDefaultToolkit().getScreenSize();
  43. Image screen =robot.createScreenCapture(new Rectangle(450,350,screenDims.width,screenDims.height)).getScaledInstance(400,300,Image.SCALE_SMOOTH);
  44. MediaTracker tracker =new MediaTracker(new Label());
  45. tracker.addImage(screen,1);
  46. try {
  47. tracker.waitForID(0);
  48. }catch(InterruptedException e) { /** ... */ }
  49. return screen;
  50. }
  51. }
  52. public class ScreenCapture extends Frame{
  53. private ImageCanvas canvas =new ImageCanvas(ImageUtils.getScreenImage());
  54. public ScreenCapture(){
  55. add(canvas);
  56. setSize(400,300);
  57. setVisible(true);
  58. Thread imageThread =new UpdateThread();
  59. imageThread.setDaemon(true);
  60. imageThread.start();
  61. }
  62. class UpdateThread extends Thread{
  63. public void run(){
  64. while(true){
  65. try {
  66. Thread.currentThread().sleep(1000);
  67. }
  68. catch (Exception ex) {
  69. }
  70. canvas.setImage(ImageUtils.getScreenImage());
  71. validate();
  72. }
  73. }
  74. }   
相关文章
相关标签/搜索