国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

Java實現屏幕截圖及剪裁

2019-11-26 15:25:50
字體:
來源:轉載
供稿:網友

Java標準API中有個Robot類,該類可以實現屏幕截圖,模擬鼠標鍵盤操作這些功能。這里只展示其屏幕截圖。

  截圖的關鍵方法createScreenCapture(Rectangle rect) ,該方法需要一個Rectangle對象,Rectangle就是定義屏幕的一塊矩形區域,構造Rectangle也相當容易:

new Rectangle(int x, int y, int width, int height),四個參數分別是矩形左上角x坐標,矩形左上角y坐標,矩形寬度,矩形高度。截圖方法返回BufferedImage對象,示例代碼:

   /**   * 指定屏幕區域截圖,返回截圖的BufferedImage對象   * @param x   * @param y   * @param width   * @param height   * @return    */   public BufferedImage getScreenShot(int x, int y, int width, int height) {    BufferedImage bfImage = null;    try {      Robot robot = new Robot();      bfImage = robot.createScreenCapture(new Rectangle(x, y, width, height));    } catch (AWTException e) {      e.printStackTrace();    }    return bfImage;  }

 如果需要把截圖保持為文件,使用ImageIO.write(RenderedImage im, String formatName, File output) ,示例代碼:

   /**   * 指定屏幕區域截圖,保存到指定目錄   * @param x   * @param y   * @param width   * @param height   * @param savePath - 文件保存路徑   * @param fileName - 文件保存名稱   * @param format - 文件格式   */  public void screenShotAsFile(int x, int y, int width, int height, String savePath, String fileName, String format) {    try {      Robot robot = new Robot();      BufferedImage bfImage = robot.createScreenCapture(new Rectangle(x, y, width, height));      File path = new File(savePath);      File file = new File(path, fileName+ "." + format);      ImageIO.write(bfImage, format, file);    } catch (AWTException e) {      e.printStackTrace();      } catch (IOException e) {      e.printStackTrace();    }  }

 捕捉屏幕截圖后,也許,我們需要對其剪裁。主要涉及兩個類CropImageFilter和FilteredImageSource,關于這兩個類的介紹,看java文檔把。

   /**   * BufferedImage圖片剪裁   * @param srcBfImg - 被剪裁的BufferedImage   * @param x - 左上角剪裁點X坐標   * @param y - 左上角剪裁點Y坐標   * @param width - 剪裁出的圖片的寬度   * @param height - 剪裁出的圖片的高度   * @return 剪裁得到的BufferedImage   */  public BufferedImage cutBufferedImage(BufferedImage srcBfImg, int x, int y, int width, int height) {    BufferedImage cutedImage = null;    CropImageFilter cropFilter = new CropImageFilter(x, y, width, height);     Image img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(srcBfImg.getSource(), cropFilter));     cutedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);     Graphics g = cutedImage.getGraphics();     g.drawImage(img, 0, 0, null);     g.dispose();     return cutedImage;  }

如果剪裁后需要保存剪裁得到的文件,使用ImageIO.write,參考上面把截圖保持為文件的代碼。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 凌云县| 祥云县| 偏关县| 华阴市| 浑源县| 石渠县| 高密市| 天峨县| 奉新县| 邵东县| 陇南市| 英吉沙县| 防城港市| 道孚县| 彰化县| 专栏| 象山县| 嵊州市| 满洲里市| 江口县| 淮阳县| 元氏县| 泗水县| 佛坪县| 榆林市| 香格里拉县| 浦江县| 石楼县| 德安县| 鹤峰县| 内乡县| 万安县| 岱山县| 个旧市| 巫山县| 冷水江市| 隆化县| 嘉善县| 桦南县| 衢州市| 辽阳市|