-
Notifications
You must be signed in to change notification settings - Fork 0
/
pywms.py
212 lines (171 loc) · 7.72 KB
/
pywms.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import sys
from timeit import default_timer as timer
import BaseHTTPServer
from urlparse import urlparse, parse_qs
from wand.image import Image
from wand.color import Color
HOST_NAME = '127.0.0.1'
PORT_NUMBER = 8181
bbox = []
crs = None
def timed_transform(left, right, bottom, top, width, height, img, func):
print('{}:{} {}:{}'.format(left, right, top, bottom))
begin = timer()
result = func(left, right, bottom, top, width, height, img)
end = timer()
print('{} duration: {} (image size: {}x{})'.format(
func.func_name,
end - begin,
right - left, top - bottom))
return result
def crop_sample(left, right, bottom, top, width, height, img):
border_width = [-left if left < 0 else 0, (right - img.width)
if right > img.width else 0]
border_height = [-bottom if bottom < 0 else 0, (top - img.height)
if top > img.height else 0]
print ('border_width={}'.format(border_width))
print ('border_height={}'.format(border_height))
copy = img[max(0, left):min(img.width, right),
max(0, bottom):min(img.height, top)]
# ...
if sum(border_width) > 0 or sum(border_height) > 0:
copy.border(Color('transparent'), sum(border_width), sum(border_height))
copy.crop(border_width[1],
border_height[1],
copy.width - border_width[0],
copy.height - border_height[0])
copy.sample(width, height)
return copy
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def end_headers (self):
self.send_header('Access-Control-Allow-Origin', '*')
BaseHTTPServer.BaseHTTPRequestHandler.end_headers(self)
def do_GET(self):
if self.path.find('SERVICE=WMS') < 0:
self.send_response(404)
self.end_headers()
return
params = parse_qs(urlparse(self.path).query)
if 'REQUEST' not in params:
self.send_response(503)
self.end_headers()
return
command = params['REQUEST'][0]
if command == 'GetMap':
# we're only interested by:
# - FORMAT=
# - BBOX=minx,miny,maxx,maxy
# - WIDTH|HEIGHT
self.send_response(200)
self.send_header('Content-type', params['FORMAT'][0])
self.end_headers()
request_bbox = [float(t) for t in params['BBOX'][0].split(',')]
dimx = bbox[2] - bbox[0]
dimy = bbox[3] - bbox[1]
print 'REQ:', request_bbox
print 'SRC:', bbox
target_width = int(params['WIDTH'][0])
target_height = int(params['HEIGHT'][0])
best_candidate = image
# If we're using a pyramidal image, pick the best one
# The best one is the smallest image where the ratio
# pixel_source/pixel_target is > 1 (== no upscaling)
if image.sequence is not None:
ratios = [(request_bbox[2+i] - request_bbox[i]) /
(bbox[2+i] - bbox[i]) for i in [0, 1]]
pixels_dest_count = [float(target_width), float(target_height)]
best_candidate = image.sequence[0]
for img in image.sequence[1:]:
pixels_source_count = [ratios[0] * img.width,
ratios[1] * img.height]
ratio = [pixels_source_count[i] / pixels_dest_count[i]]
if min(ratio) >= 1:
best_candidate = img
else:
break
print '{}x{}|,{}x{} taken from {}x{}'.format(
ratios[0], ratios[1],
target_width, target_height,
best_candidate.width, best_candidate.height)
# Compute extraction area
left = (best_candidate.width * (request_bbox[0] - bbox[0])) / dimx
right = (best_candidate.width * (request_bbox[2] - bbox[0])) / dimx
top = (best_candidate.height * ((bbox[3] - request_bbox[1])) / dimy)
bottom = (best_candidate.height * ((bbox[3] - request_bbox[3])) / dimy)
out = timed_transform(int(left), int(right),
int(bottom), int(top),
int(params['WIDTH'][0]), int(params['HEIGHT'][0]),
best_candidate,
crop_sample)
out.format = params['FORMAT'][0].split('/')[1]
out.save(file=self.wfile)
elif command == 'GetCapabilities':
self.send_response(200)
self.send_header('Content-type', 'text/xml; charset=UTF-8')
self.end_headers()
self.wfile.write(
'''<?xml version='1.0' encoding="UTF-8" standalone="no" ?>
<WMS_Capabilities version="1.3.0" xmlns="http://www.opengis.net/wms" xmlns:sld="http://www.opengis.net/sld" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wms http://schemas.opengeospatial.net/wms/1.3.0/capabilities_1_3_0.xsd http://www.opengis.net/sld http://schemas.opengeospatial.net/sld/1.1.0/sld_capabilities.xsd ">
<Service>
<Name>WMS</Name>
<Title>foofoo</Title>
<Abstract>barbar</Abstract>
<Fees>no conditions apply</Fees>
<AccessConstraints>None</AccessConstraints>
<MaxWidth>4096</MaxWidth>
<MaxHeight>4096</MaxHeight>
</Service>
<Capability>
<Request>
<GetCapabilities>
<Format>text/xml</Format>
</GetCapabilities>
<GetMap>
<Format>image/png</Format>
<Format>image/gif</Format>
<Format>image/jpeg</Format>
<Format>image/tiff</Format>
<Format>image/png; mode=8bit</Format>
</GetMap>
</Request>
<Exception>
<Format>XML</Format>
<Format>INIMAGE</Format>
<Format>BLANK</Format>
</Exception>
<Layer>
<Name>FooFoo</Name>
<Title>BarBar</Title>
<Abstract>foobarfoobar</Abstract>
<CRS>{crs}</CRS>
<EX_GeographicBoundingBox>
<westBoundLongitude>-180</westBoundLongitude>
<eastBoundLongitude>180</eastBoundLongitude>
<southBoundLatitude>-90</southBoundLatitude>
<northBoundLatitude>90</northBoundLatitude>
</EX_GeographicBoundingBox>
<BoundingBox CRS="{crs}"
minx="{minx}" miny="{miny}" maxx="{maxx}" maxy="{maxy}" />
</Layer>
</Capability>
</WMS_Capabilities>
'''.format(crs=crs, minx=bbox[0], maxx=bbox[2], miny=bbox[1], maxy=bbox[3]))
if __name__ == '__main__':
if len(sys.argv) != 4:
print('Usage: python dummywms.py image_full_path crs minx,miny,maxx,maxy')
sys.exit(1)
image = Image(filename=sys.argv[1])
crs = sys.argv[2]
bbox = [float(t) for t in sys.argv[3].split(',')]
server_class = BaseHTTPServer.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)