将geojson转为背景透明的图片
时间: 2023-09-20 16:15:09 浏览: 47
要将GeoJSON转换为具有透明背景的图片,您可以将代码稍微修改一下,以使用RGBA模式创建新图像,并将背景设置为透明。下面是一个示例代码:
```python
from PIL import Image, ImageDraw
import json
import geojson
# Load GeoJSON data
with open('your_geojson_file.geojson') as f:
data = json.load(f)
# Get bounding box coordinates
min_lon, min_lat, max_lon, max_lat = geojson.utils.coords(data)
# Calculate image size
width, height = 1024, int(1024 * ((max_lat - min_lat) / (max_lon - min_lon)))
# Create image with transparent background
img = Image.new("RGBA", (width, height), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
# Convert GeoJSON to image coordinates
coords = []
for feature in data['features']:
geometry = feature['geometry']
if geometry['type'] == 'Polygon':
for polygon in geometry['coordinates']:
xys = []
for lon, lat in polygon:
x = (lon - min_lon) / (max_lon - min_lon) * width
y = height - (lat - min_lat) / (max_lat - min_lat) * height
xys.append((x, y))
coords.append(xys)
elif geometry['type'] == 'LineString':
xys = []
for lon, lat in geometry['coordinates']:
x = (lon - min_lon) / (max_lon - min_lon) * width
y = height - (lat - min_lat) / (max_lat - min_lat) * height
xys.append((x, y))
coords.append(xys)
# Draw GeoJSON on image
for coord in coords:
draw.polygon(coord, outline='black')
# Save image with transparent background
img.save('your_output_image.png', format='PNG')
```
请将上述代码按照实际情况进行修改,并确保您已经安装了Pillow和GeoJSON库。在这个示例中,我们使用了RGBA模式并将背景设置为透明。保存图像时,我们使用PNG格式,以便保留透明度信息。