爬虫(三) 图片

直接祭出代码

public static void main(String[] args) {
		String url = "http://img3.myhsw.cn/2017-06-23/xf3peqec.jpg";
		String path = "/test/img/1.jpg";
		 getPicture1(url,path);
		// getPicture2(url,path);
	}

	// 方法一
	private static void getPicture1(String urlpath, String path) {
		URL url = null;
		try {
			url = new URL(urlpath);
			DataInputStream dataInput = new DataInputStream(url.openStream());
			FileOutputStream fileOutput = new FileOutputStream(new File(path));
			ByteArrayOutputStream output = new ByteArrayOutputStream();

			byte[] buffer = new byte[1024];
			int length;

			while ((length = dataInput.read(buffer)) > 0) {
				output.write(buffer, 0, length);
			}
			fileOutput.write(output.toByteArray());
			dataInput.close();
			fileOutput.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

    //方法二
	public static void getPicture2(String url, String path) {

		BufferedImage image = null;
		try {
			image = ImageIO.read(new URL(url));
		} catch (Exception e) {
			e.printStackTrace();
		}

		File file = new File(path).getAbsoluteFile();

		File dir = file.getParentFile();
		if (!dir.isDirectory())
			dir.mkdirs();

		System.out.println(path);
		try {
			ImageIO.write(image, "jpg", new File(path));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

两种方法都可以
直接复制的注意修改path

!!!如果图片打不开 图片格式不对
可以读取图片的格式为:[BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
文件后缀名有时候不是实际的文件格式,可以下载下来看看前缀 例如 :RIFF WEBPVP8就是webp格式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值