java 截屏 锁屏黑色_JAVA截屏生成图片文件

该Java程序使用Robot类捕获屏幕截图,并将其保存为.jpg格式的文件。程序首先获取屏幕尺寸,创建BufferedImage对象,然后通过createScreenCapture方法截取全屏。最后,使用JPEG编码器将图像压缩并保存到指定路径,同时打开文件以供查看。
摘要由CSDN通过智能技术生成

import java.awt.AWTException;

import java.awt.Desktop;

import java.awt.Dimension;

import java.awt.Rectangle;

import java.awt.Robot;

import java.awt.Toolkit;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.text.SimpleDateFormat;

import java.util.Date;

import javax.swing.filechooser.FileSystemView;

import com.sun.image.codec.jpeg.JPEGCodec;

import com.sun.image.codec.jpeg.JPEGEncodeParam;

import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class Snapshot {

private static Toolkit toolkit;

private static Robot robot;

private static BufferedImage bufferedImage = null;

public static void shot() throws AWTException, IOException {

toolkit = Toolkit.getDefaultToolkit();

robot = new Robot();

Dimension screenDimension = toolkit.getScreenSize();

bufferedImage = robot.createScreenCapture(new Rectangle(screenDimension));

String path = String.valueOf(FileSystemView.getFileSystemView().getHomeDirectory());

//System.out.println(path);

SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddHHmmss");

String name = sdf.format(new Date());

name = name+".jpg";

File file = new File(path +"\\"+ name);

OutputStream output = new FileOutputStream(file);

bufferedImage = bufferedImage.getSubimage(0, 0, screenDimension.width,screenDimension.height);

JPEGEncodeParam param = JPEGCodec.getDefaultJPEGEncodeParam(bufferedImage);

param.setQuality(0.7F, false);

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output, param);

encoder.encode(bufferedImage);

encoder.getOutputStream().close();

Desktop.getDesktop().open(new File(path));

Runtime.getRuntime().exec("cmd /c " + path + name);

}

public static void main(String[] args) throws AWTException, IOException {

shot();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值