天地图切片下载优化方案 ez_tdt_title_download.py
from ez_title_index import lng_lat_to_title_index
import requests
#Pillow
from PIL import Image
import os
文件存放位置设置
BASE_PATH = os.path.join(os.path.abspath(os.curdir), 'disc')
BASE_PATH_res = os.path.join(os.path.abspath(os.curdir), 'result')
简单反爬虫 , 可以不写
headers = {
"Connection": "keep-alive",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
}
#下载瓦片
def download_pic(x, y, z):
"""
下载地图
:param x: x 范围
:param y: y 范围
:param z: int
"""
try:
# 下载图片
key = 'a4ee5c551598a1889adfabff55a5fc27'
for xi in x:
xpathlayer = os.path.join(BASE_PATH, str(z))#地图层目录
if (os.path.exists(xpathlayer) == False):
os.mkdir(xpathlayer)
xpath = os.path.join(xpathlayer, str(xi))#地图X坐标目录
if(os.path.exists(xpath)==False):
os.mkdir(xpath)
for yi in y:
#url = "http://t2.tianditu.gov.cn/DataServer?T=img_w&x={}&y={}&l={}&tk={}".format(xi, yi, z, key)
url = "http://t3.tianditu.gov.cn/DataServer?T=img_w&x={}&y={}&l={}&tk={}".format(xi, yi, z, key)
# 保存文件名称
fileName = os.path.join(xpath, "{}.png".format(yi))
# 具体下载操作
if (os.path.exists(fileName)) == False:
r = requests.get(url=url, headers=headers)
if r.status_code == 200:
with open(fileName, 'wb') as f:
for chunk in r:
f.write(chunk)
else:
print("访问异常")
except Exception as e:
print(e)
pass
#合并瓦片
def merge_pic(x, y, z):
"""
合并下载地图
:param x: x 范围
:param y: y 范围
:param z: int
:return:
"""
picSize = 256
try:
# 构造平图矩阵
li = []
for xi in x:
xpathlayer = os.path.join(BASE_PATH, str(z)) # 地图层目录
xpath = os.path.join(xpathlayer, str(xi)) # 地图X坐标目录
lis = []
for yi in y:
fileName = os.path.join(xpath, "{}.png".format(yi))
lis.append(fileName)
li.append(lis)
oca = len(x)
ocb = len(y)
toImage = Image.new('RGBA', (oca * picSize, ocb * picSize))
for i in range(oca):
for j in range(ocb):
fromImge = Image.open(li[i][j])
picx = 256 * i
picy = 256 * j
loc = (picx, picy)
toImage.paste(fromImge, loc)
toImage.save(os.path.join(BASE_PATH_res, "rs{}.png".format(z)))
print("构造完成输出图片")
except Exception as e:
print(e)
pass
def run_spider(z, minx, maxx, miny, maxy):
"""
下载切片地图
:param z:放大级别
:param minx: 最小x
:param maxx: 最大x
:param miny: 最小y
:param maxy: 最大y
:return:
"""
#z = 18
xy = [minx, miny]#左下角 经纬度坐标
xxyy = [maxx, maxy]#右上角 经纬度坐标
minxy = lng_lat_to_title_index(xy[0], xy[1], z) #转换后的瓦片坐标
maxxy = lng_lat_to_title_index(xxyy[0], xxyy[1], z) #转换后的瓦片坐标
xr = range(minxy[0], maxxy[0]+1)
yr = range( maxxy[1],minxy[1]+1)
download_pic(xr, yr, z)#下载瓦片
merge_pic(xr, yr, z)#合并瓦片成为大图
if name == 'main':
run_spider(z=15, minx=121.315498352051, maxx=121.338307857513, miny=30.6949805750931, maxy=30.7056264386052)