用java实现了一个小巧的截图工具,完全媲美微信QQ的截图工具。支持托盘区显示小图标,快捷键启动截图。
1.先看效果:
2.项目截图
3.代码
pom.xml
<build>
<finalName>itxw-cutScreen</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>net.itxw.CutScreen</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>6</source>
<target>6</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.melloware/jintellitype -->
<dependency>
<groupId>com.melloware</groupId>
<artifactId>jintellitype</artifactId>
<version>1.3.9</version>
</dependency>
</dependencies>
主类:
package net.itxw;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.melloware.jintellitype.HotkeyListener;
import com.melloware.jintellitype.IntellitypeListener;
import com.melloware.jintellitype.JIntellitype;
/**
* @Author: houyong 另一中实现 参考而已
* @Date: 2019/9/19
*/
public class CutScreen implements HotkeyListener, IntellitypeListener {
private final int HOTKET=111;
public static void main(String[] args) {
new CutScreen().setTray();
}
public CutScreen() {
//添加监听
if (JIntellitype.isJIntellitypeSupported()) {
//注册热键快捷键
JIntellitype.getInstance().registerHotKey(HOTKET, JIntellitype.MOD_CONTROL+JIntellitype.MOD_ALT, 'X');
//启动监听
JIntellitype.getInstance().addHotKeyListener(this);
JIntellitype.getInstance().addIntellitypeListener(this);
}
}
/**
* 快捷键组合键按键事件
* @param i
*/
@Override
public void onHotKey(int i) {
System.out.println(i);
//如果是我指定的快捷键就执行指定的操作
if(i==HOTKET){
startCut();
}
}
@Override
public void onIntellitype(int i) {
System.out.println(i);
}
public void startCut() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ScreenShotWindow cutScreenWin=new ScreenShotWindow();
cutScreenWin.setVisible(true);
cutScreenWin.toFront();
} catch (AWTException e) {
e.printStackTrace();
} finally {
}
}
});
}
//添加托盘显示:1.先判断当前平台是否支持托盘显示
public void setTray() {
if(SystemTray.isSupported()){//判断当前平台是否支持托盘功能
//创建托盘实例
SystemTray tray = SystemTray.getSystemTray();
//创建托盘图标:1.显示图标Image 2.停留提示text 3.弹出菜单popupMenu 4.创建托盘图标实例
//1.创建Image图像
URL fileURL = CutScreen.class.getResource("image/itxw.jpg");
Image image = Toolkit.getDefaultToolkit().getImage(fileURL);
//2.停留提示text
String text = "IT学问网截图";
//3.弹出菜单popupMenu
PopupMenu popMenu = new PopupMenu();
MenuItem itmOpen = new MenuItem("截图");
itmOpen.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
startCut();
}
});
MenuItem itmExit = new MenuItem("退出");
itmExit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
popMenu.add(itmOpen);
popMenu.add(itmExit);
//创建托盘图标
TrayIcon trayIcon = new TrayIcon(image,text,popMenu);
//将托盘图标加到托盘上
try {
tray.add(trayIcon);
} catch (AWTException e1) {
e1.printStackTrace();
}
}
}
}
截屏窗口类:
package net.itxw;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Author: houyong
* @Date: 2019/9/20
*/
/*
* 截图窗口
*/
class ScreenShotWindow extends JWindow
{
private int orgx, orgy, endx, endy;
private BufferedImage image=null;
private BufferedImage tempImage=null;
private BufferedImage saveImage=null;
private ToolsWindow tools=null;
public ScreenShotWindow() throws AWTException {
//获取屏幕尺寸
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
this.setBounds(0, 0, d.width, d.height);
this.setSize(d.width, d.height);
this.toFront();
this.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
//截取屏幕
Robot robot = new Robot();
image = robot.createScreenCapture(new Rectangle(0, 0, d.width,d.height));
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
tools.dispose();
dispose();
}
}
@Override
public void mousePressed(MouseEvent e) {
//鼠标松开时记录结束点坐标,并隐藏操作窗口
orgx = e.getX();
orgy = e.getY();
if(tools!=null){
tools.setVisible(false);
}
}
@Override
public void mouseReleased(MouseEvent e) {
//鼠标松开时,显示操作窗口
if(tools==null){
tools=new ToolsWindow(ScreenShotWindow.this,e.getX(),e.getY());
}else{
tools.setLocation(e.getX(),e.getY());
}
tools.setVisible(true);
tools.toFront();
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
//鼠标拖动时,记录坐标并重绘窗口
endx = e.getX();
endy = e.getY();
//临时图像,用于缓冲屏幕区域放置屏幕闪烁
Image tempImage2=createImage(ScreenShotWindow.this.getWidth(),ScreenShotWindow.this.getHeight());
Graphics g =tempImage2.getGraphics();
g.drawImage(tempImage, 0, 0, null);
int x = Math.min(orgx, endx);
int y = Math.min(orgy, endy);
int width = Math.abs(endx - orgx)+1;
int height = Math.abs(endy - orgy)+1;
// 加上1防止width或height0
g.setColor(Color.BLUE);
g.drawRect(x-1, y-1, width+1, height+1);
//减1加1都了防止图片矩形框覆盖掉
saveImage = image.getSubimage(x, y, width, height);
g.drawImage(saveImage, x, y, null);
ScreenShotWindow.this.getGraphics().drawImage(tempImage2,0,0,ScreenShotWindow.this);
}
});
}
@Override
public void paint(Graphics g) {
RescaleOp ro = new RescaleOp(0.8f, 0, null);
tempImage = ro.filter(image, null);
g.drawImage(tempImage, 0, 0, this);
}
//识别图像到
public void ocrImage() throws IOException {
// JFileChooser jfc=new JFileChooser();
// jfc.setDialogTitle("保存");
//
// //文件过滤器,用户过滤可选择文件
// FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG", "jpg");//过滤文件名,只显示jpg格式文件
// jfc.setFileFilter(filter); //将文件过滤器加入到文件选择中
//
// //初始化一个默认文件(此文件会生成到桌面上)
// SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddHHmmss");
// String fileName = sdf.format(new Date()); //把时间作为图片名(防止图片名重复,而把之前的图片覆盖)
// File filePath = FileSystemView.getFileSystemView().getHomeDirectory(); //获取系统桌面的路径
// File defaultFile = new File(filePath + File.separator + fileName + ".jpg");
// jfc.setSelectedFile(defaultFile);
//
// int flag = jfc.showSaveDialog(this);
// if(flag==JFileChooser.APPROVE_OPTION){
// File file=jfc.getSelectedFile();
// String path=file.getPath();
// //检查文件后缀,放置用户忘记输入后缀或者输入不正确的后缀
// if(!(path.endsWith(".jpg")||path.endsWith(".JPG"))){
// path+=".jpg";
// }
// //写入文件
// ImageIO.write(saveImage,"jpg",new File(path));
// dispose();
// tools.dispose();
// }
String data="houyong ocr";
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(new StringSelection(data), null);
dispose();
tools.dispose();
}
//保存图像到文件
public void saveImage() throws IOException {
JFileChooser jfc=new JFileChooser();
jfc.setDialogTitle("保存");
//文件过滤器,用户过滤可选择文件
FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG", "jpg");//过滤文件名,只显示jpg格式文件
jfc.setFileFilter(filter); //将文件过滤器加入到文件选择中
//初始化一个默认文件(此文件会生成到桌面上)
SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddHHmmss");
String fileName = sdf.format(new Date()); //把时间作为图片名(防止图片名重复,而把之前的图片覆盖)
File filePath = FileSystemView.getFileSystemView().getHomeDirectory(); //获取系统桌面的路径
File defaultFile = new File(filePath + File.separator + fileName + ".jpg");
jfc.setSelectedFile(defaultFile);
int flag = jfc.showSaveDialog(this);
if(flag==JFileChooser.APPROVE_OPTION){
File file=jfc.getSelectedFile();
String path=file.getPath();
//检查文件后缀,放置用户忘记输入后缀或者输入不正确的后缀
if(!(path.endsWith(".jpg")||path.endsWith(".JPG"))){
path+=".jpg";
}
//写入文件
ImageIO.write(saveImage,"jpg",new File(path));
dispose();
tools.dispose();
}
}
}
小工具类:
package net.itxw;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
/**
* @Author: houyong
* @Date: 2019/9/20
*/
/*
* 操作窗口
*/
class ToolsWindow extends JWindow
{
private ScreenShotWindow parent;
public ToolsWindow(ScreenShotWindow parent,int x,int y) {
this.parent=parent;
this.init();
this.setLocation(x, y);
this.pack();
this.setVisible(true);
}
private void init(){
this.setLayout(new BorderLayout());
JToolBar toolBar=new JToolBar("Java 截图");
//确定按钮 保存图片到剪贴板
JButton ocrButton=new JButton("识别");
ocrButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
parent.ocrImage();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
toolBar.add(ocrButton);
//确定按钮 保存图片到剪贴板
JButton confirmButton=new JButton("确定");
confirmButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
parent.saveImage();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
toolBar.add(confirmButton);
//保存按钮
JButton saveButton=new JButton("保存");
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
parent.saveImage();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
toolBar.add(saveButton);
//关闭按钮
JButton closeButton=new JButton("取消");
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
parent.dispose();
}
});
toolBar.add(closeButton);
this.add(toolBar,BorderLayout.NORTH);
}
}