JAVA实现自动打开URL对应的网页并保存为图片-不借助第三方API

基本原理:

JDK6u10版本以上提供了DeskTop的API接口支持,可以根据URI参数自动打开

操作系统默认的浏览器来加载对应的网页,同时借助JDK的Robot类实现自动截屏

这样就完成了对任意一个URL对应网页保存为图片。程序如下:

package com.gloomyfish.image.util;

import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URI;

import javax.imageio.ImageIO;

public class DeskTopTest {
	public static void main(String[] args) {
		if (!java.awt.Desktop.isDesktopSupported()) {
			System.err.println("Desktop is not supported (fatal)");
			System.exit(1);
		}

		java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
		if (!desktop.isSupported(java.awt.Desktop.Action.BROWSE)) {
			System.err.println("Desktop doesn't support the browse action (fatal)");
			System.exit(1);
		}
		
		try {
			URI uri = URI.create("http://www.csdn.net");
			desktop.browse(uri);
			Thread.sleep(8000); // 8 seconds is enough to load the any page.
			Robot robot = new Robot();
			// Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize() );
			Rectangle rectangle = new Rectangle(300, 90, 1000, 720);
			BufferedImage image = robot.createScreenCapture(rectangle);
			File outputfile = new File("D:\\agriculture\\test.jpg");
			ImageIO.write(image, "jpg", outputfile);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (AWTException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} 
	}
}
缺点:

程序运行时用户不能有其它操作,否则可能保存错误截屏。 这里

假设加载一个网页时间最长为8秒.

转载请注明出自gloomyfish


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gloomyfish

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值