package cn.com.tenlion.buildingpictures.util;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 百度地图相关工具类
 * ClassName: BaiDuMapUtil
 * @Description: TODO
 * 创建工具: MyEclipse2014
 * 运行环境: [Tomcat7以上,MySql5.6以上,JDK7以上]
 * @author 崔宝铖
 * @date 2019年6月19日
 */
public class BaiDuMapUtil {
	
	/** 百度地图开发Key */
	private static String ak = "VchhMAkuOzvkaI0NcZSNNippil968u9G";

	public static BufferedImage getImage(String center, Integer width, Integer height) throws IOException {
		URL url = new URL("http://api.map.baidu.com/staticimage/v2?ak=" + ak + "&width=" + width + "&height=" + ( height + 15) + "&center=" + center + "&zoom=15&copyright=1");
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		//设置超时间为5秒
		conn.setConnectTimeout(5*1000);
		//防止屏蔽程序抓取而返回403错误
		conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
		//得到输入流
		InputStream inputStream = conn.getInputStream();
		//获取自己数组
		byte[] getData = readInputStream(inputStream);
		BufferedImage image = ImageIO.read(new ByteArrayInputStream(getData));
		return image.getSubimage(0, 0, width, height);
	}

	private static byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}
	
}
