工作中遇到让java后台通过经纬度获取一张位置截图上传,经过研究之后实现,是通过百度地图api中提供的一个接口实现的。
源码如下:
/**
* 通过传入的url获取图片流,并上传返回key。----百度地图静态截图
* @Title: download
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param remoteFilePath
* @return String
* 2017年8月14日下午4:02:34
*/
public static String downloadBaiduImg(String remoteFilePath) {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] bs = new byte[1024];
try {
URL url = new URL(remoteFilePath);
URLConnection con = url.openConnection();
con.setConnectTimeout(5 * 1000);
InputStream is = con.getInputStream();
int len = 0;
while( (len=is.read(bs)) != -1 ){
outStream.write(bs, 0, len);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//下面的代码是上传到文件服务器的代码
String ext = "jpg";//remoteFilePath.substring(remoteFilePath.lastIndexOf(".")+1);
String fileName = "baidudingwei";//remoteFilePath.substring(remoteFilePath.lastIndexOf("/")+1,remoteFilePath.lastIndexOf("."));
FastDFSFile file = new FastDFSFile(outStream.toByteArray(),ext);
NameValuePair[] meta_list = new NameValuePair[4];
meta_list[0] = new NameValuePair("fileName", fileName);
meta_list[1] = new NameValuePair("fileLength", String.valueOf(bs.length));
meta_list[2] = new NameValuePair("fileExt", ext);
meta_list[3] = new NameValuePair("fileAuthor", "Wavenet");
String filePath = FileManager.upload(file,meta_list);
return filePath;
}
调用方法如下:
String ss = "http://api.map.baidu.com/staticimage/v2?";
ss += "ak="+bdkey+"&width=500";//bdkey=百度地图开放的开发者的key值,申请一个就好了
ss += "&height=400&zoom=16&markers="+lng+","+lat;//lng为定位位置的经度,lat为纬度
bdimg = FileManager.downloadBaiduImg(ss);//bdimg为上传成功之后访问图片的链接
这里记录一下。调用方法拼的字符串ss中的width,height为截图的大小设置。
api详情见:http://lbsyun.baidu.com/index.php?title=static
文件服务器的上传见:http://download.csdn.net/download/it_java_shuai/9960309