第一步:创建截屏工具类
1 import java.awt.AWTException; 2 import java.awt.Dimension; 3 import java.awt.Rectangle; 4 import java.awt.Robot; 5 import java.awt.Toolkit; 6 import java.awt.image.BufferedImage; 7 import java.io.File; 8 import java.io.IOException; 9 import javax.imageio.ImageIO; 10 11 /** 12 * 截屏工具类 13 * @author coil 14 * 15 */ 16 public class CutPicUtil { 17 18 /** 19 * 屏幕截图 20 * @param imageName 存储图片名称 21 * @param path 图片路径 22 * @param imgType 图片类型 23 * @throws AWTException 24 * @throws IOException 25 */ 26 public static void cutPic(String imageName,String path,String imgType) throws AWTException, IOException{ 27 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 28 Rectangle screenRectangle = new Rectangle(screenSize); 29 Robot robot = new Robot(); 30 BufferedImage image = robot.createScreenCapture(screenRectangle); 31 ImageIO.write(image,imgType, new File(path+imageName+"."+imgType)); 32 } 33 34 }
第二步:在服务层调用截图工具类
1 @Override 2 public Map<String, Object> ScreenshotImg(String imageName, String basePath,String path, 3 String imgType) { 4 Map<String, Object> map = new HashMap<String, Object>(); 5 boolean flag = true; 6 String name = DateUtil.getNowDate(6)+RandomUtil.getRandomString(8); 7 try { 8 CutPicUtil.cutPic(name, basePath+path,imgType); 9 } catch (AWTException e) { 10 // TODO Auto-generated catch block 11 e.printStackTrace(); 12 flag = false; 13 } catch (IOException e) { 14 // TODO Auto-generated catch block 15 e.printStackTrace(); 16 flag = false; 17 } 18 if(flag){ 19 map.put("state","0");//截屏成功 20 map.put("path",path+name+"."+imgType); 21 }else{ 22 map.put("state","1");//截屏失败 23 } 24 return map; 25 }
第三步:在控制层提供接口
1 /** 2 * 屏幕截图 3 * @return 4 */ 5 @RequestMapping(value="cutPic" ,method=RequestMethod.POST) 6 @ResponseBody 7 public Map<String, Object> cutPic(HttpServletRequest request){ 8 String imageName = DateUtil.getNowDate(6)+RandomUtil.getRandomString(6); 9 String basePath = request.getRealPath("/"); 10 String path = "/static/img/Screenshotimg/"; 11 return iManageService.ScreenshotImg(imageName,basePath,path, "jpg"); 12 }
第四步:前台页面调用接口(这里使用原生js调用)
1 <img id="jietu" width="300px" height="180px"></br> 2 <button id="jt">截屏</button> 3 <script type="text/javascript"> 4 $("#jt").click(function(){ 5 $.ajax({ 6 url:"router/cutPic", 7 type:"post", 8 data:{}, 9 success:function(data){ 10 if(data.state=="0"){ 11 alert("截屏成功"); 12 $("#jietu").attr("src","/wxactive"+data.path); 13 }else{ 14 alert("截图失败"); 15 } 16 window.clearInterval(timer); 17 console.log(data); 18 }, 19 error:function(e){ 20 alert("错误!!"); 21 window.clearInterval(timer); 22 } 23 }); 24 }); 25 </script>