java截图程序代码 截图的程序

java截屏有哪几种方法

前台方式

创新互联建站网站建设由有经验的网站设计师、开发人员和项目经理组成的专业建站团队,负责网站视觉设计、用户体验优化、交互设计和前端开发等方面的工作,以确保网站外观精美、成都做网站、网站建设易于使用并且具有良好的响应性。

1. 利用html2canvas实现前台截屏

html2canvas项目的gitHub地址

html2canvas示例

html2canvas可以将HTML代码块进行截取,并生成快照形式的canvas,然后可以利用html5的下载功能提供图片的下载接口,供用户下载。

优点:前台技术,实现比较容易。

缺点:此项目使用了html5的技术,因此在对IE的兼容上,只可以在IE9+的版本上使用。

使用时,需要引用jQuery.js和html2canvas.js。(html2canvas.js可以在github上下载)

具体JavaScript代码如下:

var canvas = function () {

html2canvas($("#chart"), {

onrendered: function (canvas) {

$("#class11").html(canvas);//将id为“class11”部分的代码转换为canvas

var type = 'png';//图片类型为png

var imgData = canvas.toDataURL('png');//将图片转换为png类型的流

var _fixType = function (type) {

type = type.toLowerCase().replace(/jpg/i, 'jpeg'); var r = type.match(/png|jpeg|bmp|gif/)[0]; return 'image/' + r;

}; var saveFile = function (data, filename) {

var save_link = document.createElementNS('', 'a');

save_link.href = data;

save_link.download = filename; var event = document.createEvent('MouseEvents');

event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

save_link.dispatchEvent(event);

}; //下载时的文件名

var filename = 'baidufe_' + (new Date()).getTime() + '.' + type; // 下载文件

saveFile(imgData, filename);

}

});

后台方式(java)

1. 利用html2image实现

html2image的地址(google)

html2image是可以识别html标签并将html转换成图片的java项目。

优点:后台转换,故对浏览器的版本基本没有要求。

缺点:对样式的识别不是很好,转换出来的图片比较简单,基本没有可以兼容的样式。

使用方式:maven中引用如下依赖:

dependency

groupIdcom.github.xuwei-k/groupId

artifactIdhtml2image/artifactId

version0.1.0/version/dependency12345

2. 利用DJNativeSwing项目实现

纯java代码实现。使用DJNativeSwing这个项目,构建一个swing浏览器,打开网址,之后截取图片。(需要eclipse的swt库支持)

优点:纯java实现。

缺点:需要多线程的支持,只在控制台方式实现过(由于本人对于多线程的掌握较弱,目前没有在spring项目中实现这个方法,求大神指导~~)

3. 利用phantomJs实现

phantomJs的GitHub地址

phantomJs官网

phantom利用的是webKit内核,全面支持web而不需浏览器支持,快速,原生支持各种Web标准。

优点:速度快,使用简单。

缺点:需要在项目的服务器端引用exe文件进行截图,并发性能有待考证。

Java如何实现截图功能

下面给你介绍将全屏幕截图保存到指定目录下的代码,希望能对你有帮助:

核心代码为:snapShot方法中的相关逻辑

package Jietu;

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 javax.imageio.ImageIO;

public class CameraTest {

private String filePreStr; // 默认前缀(选择存储路径例如: D:\\)

private String defName = "cameraImg"; // 默认截图名称

static int serialNum = 0; //截图名称后面的数字累加

private String imageFormat; // 图像文件的格式

private String defaultImageFormat = "png"; //截图后缀

Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); //获取全屏幕的宽高尺寸等数据

public CameraTest() {

filePreStr = defName;

imageFormat = defaultImageFormat;

}

public CameraTest(String s, String format) {

filePreStr = s;

imageFormat = format;

}

public void snapShot() {

try {

// *** 核心代码 *** 拷贝屏幕到一个BufferedImage对象screenshot

BufferedImage screenshot = (new Robot()).createScreenCapture(new Rectangle(0, 0, (int) d.getWidth(), (int) d.getHeight()));

serialNum++;

// 根据文件前缀变量和文件格式变量,自动生成文件名

String name = filePreStr + String.valueOf(serialNum) + "." + imageFormat;

File f = new File(name);

System.out.print("Save File " + name);

// 将screenshot对象写入图像文件

ImageIO.write(screenshot, imageFormat, f);

System.out.print("..Finished!\n");

} catch (Exception ex) {

System.out.println(ex);

}

}

// 运行之后,即可将全屏幕截图保存到指定的目录下面br // 配合前端页面上面的选择尺寸等逻辑,传到后台,即可实现自由选择截图区域和大小的截图br

public static void main(String[] args) {

CameraTest cam = new CameraTest("d:\\Hello", "png");//

cam.snapShot();

}

}

java 截屏程序,该怎么处理

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

import java.awt.event.MouseMotionListener;

public class sa extends JFrame {

private static final long serialVersionUID = -267804510087895906L;

private JButton button = null;

private JLabel imgLabel = null;

public sa() {

button = new JButton("模拟屏幕(点右键退出)");

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

try {

new ScreenWindow(imgLabel);

} catch (Exception e1) {

JOptionPane.showConfirmDialog(null, "出现意外错误!", "系统提示", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);

}

}

});

JPanel pane = new JPanel();

pane.setBackground(Color.WHITE);

imgLabel = new JLabel();

pane.add(imgLabel);

JScrollPane spane = new JScrollPane(pane);

this.getContentPane().add(button, BorderLayout.NORTH);

this.getContentPane().add(spane);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.setSize(300, 200);

this.setLocationRelativeTo(null);

this.setVisible(true);

}

public static void main(String[] args) {

new sa();

}

}

class ScreenWindow extends JFrame {

private static final long serialVersionUID = -3758062802950480258L;

private boolean isDrag = false;

private int x = 0;

private int y = 0;

private int xEnd = 0;

private int yEnd = 0;

public ScreenWindow(final JLabel imgLabel) throws AWTException, InterruptedException {

Dimension screenDims = Toolkit.getDefaultToolkit().getScreenSize();

JLabel label = new JLabel(new ImageIcon(ScreenImage.getScreenImage(0, 0, screenDims.width, screenDims.height)));

label.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));

label.addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) {

if (e.getButton() == MouseEvent.BUTTON3) {

dispose();

}

}

public void mousePressed(MouseEvent e) {

x = e.getX();

y = e.getY();

}

public void mouseReleased(MouseEvent e) {

if (isDrag) {

xEnd = e.getX();

yEnd = e.getY();

if(x xEnd){

int temp = x;

x = xEnd;

xEnd = temp;

}

if(y yEnd){

int temp = y;

y = yEnd;

yEnd = temp;

}

try {

imgLabel.setIcon(new ImageIcon(ScreenImage.getScreenImage(x, y, xEnd - x, yEnd - y)));

} catch (Exception ex) {

JOptionPane.showConfirmDialog(null, "出现意外错误!", "系统提示", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);

}

dispose();

}

}

});

label.addMouseMotionListener(new MouseMotionListener() {

public void mouseDragged(MouseEvent e) {

if(!isDrag)

isDrag = true;

}

public void mouseMoved(MouseEvent e) {

/** 拖动过程的虚线选取框需自己实现 */

}

});

this.setUndecorated(true);

this.getContentPane().add(label);

this.setSize(screenDims.width, screenDims.height);

this.setVisible(true);

this.setExtendedState(JFrame.MAXIMIZED_BOTH);

}

}

class ScreenImage {

public static Image getScreenImage(int x, int y, int w, int h) throws AWTException, InterruptedException {

Robot robot = new Robot();

Image screen = robot.createScreenCapture(new Rectangle(x, y, w, h)).getScaledInstance(w, h, Image.SCALE_SMOOTH);

MediaTracker tracker = new MediaTracker(new Label());

tracker.addImage(screen, 1);

tracker.waitForID(0);

return screen;

}

}

java 实现截屏!

主要是利用java的几个先有的函数,如Robot这个类的一个方法createScreenCapture一个获得一个任意大小的屏幕图像(在这里是全屏图像),而所谓的截图就是在这个图像上画出一个矩形,再利用上面的方法获得这部分的图像,程序中的cf.setAlwaysOnTop(true)是必需的;看起来是在屏幕上截图,其实只是在一个在一个内镶有桌面背景的JFrame中截图。不知道还有没有其他的好方法~

附上代码:

import java.awt.*;

import java.awt.image.*;

import java.awt.event.*;

import java.io.File;

import javax.imageio.ImageIO;

import javax.swing.*;

public class Camera {

/**

* @param args

*/

public static void main(String[] args) {

CameraJFrame cf=new CameraJFrame();

cf.setAlwaysOnTop(true);

cf.setUndecorated(true);

cf.setVisible(true);

}

}

class CameraJFrame extends JFrame

{

/**

*

*/

private static final long serialVersionUID = 1L;

Dimension di=Toolkit.getDefaultToolkit().getScreenSize();

public CameraJFrame()

{

setSize(di);

getContentPane().add(new CameraJPanel());

}

class CameraJPanel extends JPanel implements MouseListener,MouseMotionListener

{

/**

* flag主要是用来判别状态。

* 文件的格式名是unname+数字编号,格式是png

*/

private static final long serialVersionUID = 1L;

BufferedImage bi,get;

int startx,starty,endx,endy;

int flag=1;

String filename="unname";

String fileformat="png";

int count=1;

public CameraJPanel()

{

try

{

Robot ro=new Robot();

bi=ro.createScreenCapture(new Rectangle(0,0,di.width,di.height));

}

catch(Exception e)

{

e.printStackTrace();

}

addMouseListener(this);

addMouseMotionListener(this);

}

public void paintComponent(Graphics g)

{

g.drawImage(bi,0,0,di.width,di.height,this);

g.setColor(Color.red);

g.drawRect(startx, starty, endx-startx, endy-starty);

}

public void mouseClicked(MouseEvent e) {

// TODO Auto-generated method stub

if(e.getButton()==MouseEvent.BUTTON3)

{

System.exit(0);

}

else if(e.getClickCount()==2)

{

try

{

Robot ro=new Robot();

get=ro.createScreenCapture(new Rectangle(startx,starty,endx-startx,endy-starty));

String name=filename+String.valueOf(count++)+"."+fileformat;

File f=new File(name);

ImageIO.write(get, fileformat, f);

}

catch(Exception ex)

{

ex.printStackTrace();

}

flag=1; //置flag为1,以便重新开始截图。

startx=starty=endx=endy=0;

repaint();

}

}

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e) {}

public void mousePressed(MouseEvent e) {

if(flag==1)

{

startx=e.getX();

starty=e.getY();

}

}

public void mouseReleased(MouseEvent e) {

flag=0;

}

public void mouseDragged(MouseEvent e) {

flag=1;

endx=e.getX();

endy=e.getY();

repaint();

}

public void mouseMoved(MouseEvent e) {}

}

}

java 怎么实现网页截图

代码如下

[java]

span style="font-size:18px;"package com.util;

import java.awt.AWTException;

import java.awt.Desktop;

import java.awt.Dimension;

import java.awt.Graphics;

import java.awt.Image;

import java.awt.Rectangle;

import java.awt.Robot;

import java.awt.Toolkit;

import java.awt.event.KeyEvent;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;

import java.net.URISyntaxException;

import java.net.URL;

import javax.imageio.ImageIO;

public class CutPicture {

public static void main(String[] args) throws Exception,

IOException, URISyntaxException, AWTException {

// 此方法仅适用于JdK1.6及以上版本

Desktop.getDesktop().browse(new URL("").toURI());

Robot robot = new Robot();

robot.delay(10000);

Dimension d = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());

int width = (int) d.getWidth();

int height = (int) d.getHeight();

// 最大化浏览器

robot.keyRelease(KeyEvent.VK_F11);

robot.delay(2000);

Image image = robot.createScreenCapture(new Rectangle(0, 0, width,height));

BufferedImage bi = new BufferedImage(width, height,

BufferedImage.TYPE_INT_RGB);

Graphics g = bi.createGraphics();

g.drawImage(image, 0, 0, width, height, null);

// 保存图片

ImageIO.write(bi, "jpg", new File("c:/open.jpg"));

}

}/span

java 实现截图并且 保存在本地

import java.awt.AWTException;

import java.awt.Color;

import java.awt.Dimension;

import java.awt.Graphics;

import java.awt.GraphicsDevice;

import java.awt.GraphicsEnvironment;

import java.awt.Rectangle;

import java.awt.Robot;

import java.awt.Toolkit;

import java.awt.event.KeyAdapter;

import java.awt.event.KeyEvent;

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;

import javax.imageio.ImageIO;

import javax.swing.JFrame;

import javax.swing.filechooser.FileSystemView;

/**

* java截屏

* 运行后将当前屏幕截取,并最大化显示。

* 拖拽鼠标,选择自己需要的部分。

* 按Esc键保存图片到桌面,并退出程序。

* 点击右上角(没有可见的按钮),退出程序,不保存图片。

*

* @author JinCeon

*/

public class SnapshotTest {

public static void main(String[] args) {

// 全屏运行

RectD rd = new RectD();

GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment()

.getDefaultScreenDevice();

gd.setFullScreenWindow(rd);

}

}

class RectD extends JFrame {

private static final long serialVersionUID = 1L;

int orgx, orgy, endx, endy;

Dimension d = Toolkit.getDefaultToolkit().getScreenSize();

BufferedImage image;

BufferedImage tempImage;

BufferedImage saveImage;

Graphics g;

@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 RectD() {

snapshot();

setVisible(true);

// setSize(d);//最大化窗口

setDefaultCloseOperation(EXIT_ON_CLOSE);

this.addMouseListener(new MouseAdapter() {

public void mousePressed(MouseEvent e) {

orgx = e.getX();

orgy = e.getY();

}

});

this.addMouseMotionListener(new MouseMotionAdapter() {

public void mouseDragged(MouseEvent e) {

endx = e.getX();

endy = e.getY();

g = getGraphics();

g.drawImage(tempImage, 0, 0, RectD.this);

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或height为0

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, RectD.this);

}

});

this.addKeyListener(new KeyAdapter() {

@Override

public void keyReleased(KeyEvent e) {

// 按Esc键退出

if (e.getKeyCode() == 27) {

saveToFile();

System.exit(0);

}

}

});

}

public void saveToFile() {

SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddHHmmss");

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

File path = FileSystemView.getFileSystemView().getHomeDirectory();

String format = "jpg";

File f = new File(path + File.separator + name + "." + format);

try {

ImageIO.write(saveImage, format, f);

} catch (IOException e) {

e.printStackTrace();

}

}

public void snapshot() {

try {

Robot robot = new Robot();

Dimension d = Toolkit.getDefaultToolkit().getScreenSize();

image = robot.createScreenCapture(new Rectangle(0, 0, d.width,

d.height));

} catch (AWTException e) {

e.printStackTrace();

}

}

}


当前标题:java截图程序代码 截图的程序
文章出自:http://hbruida.cn/article/dosohoc.html