国产探花免费观看_亚洲丰满少妇自慰呻吟_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,參考上面把截圖保持為文件的代碼。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 客服| 辽中县| 厦门市| 广安市| 临夏县| 建昌县| 兖州市| 哈尔滨市| 日土县| 灵宝市| 武清区| 土默特右旗| 韩城市| 崇文区| 金沙县| 湟中县| 视频| 阳原县| 朝阳市| 大埔区| 钟山县| 通江县| 夏津县| 清苑县| 阳朔县| 哈尔滨市| 盈江县| 界首市| 达州市| 金堂县| 敦煌市| 建阳市| 织金县| 胶州市| 乃东县| 宜丰县| 客服| 外汇| 沙河市| 玉田县| 增城市|