Skip to content

Automate SHP to JPG creation

An answer to this question on the GIS Stack Exchange.

Question

Does anyone know of a way to batch convert shapefiles to jpegs or another common image format?

edit: I should have clarified that I would like to apply a styling to each shapefile, and then export the shapefile with that styling to an image.

For example, I have census tracts in a county, and I want an image of each individual tract highlighted while the other tracts are all the same color.

Answer

Here's a Python script I use. It can modified to change the colour of the polygons, &c:

#!/usr/bin/env python3
from descartes import PolygonPatch
import matplotlib.pyplot as plt 
import random
import shapefile
import sys
def get_cmap(n, name='hsv'):
  '''Returns a function that maps each index in 0, 1, ..., n-1 to a distinct 
  RGB color; the keyword argument name must be a standard mpl colormap name.'''
  return plt.cm.get_cmap(name, n)
if len(sys.argv)!=3:
  print("Syntax: {0} <Shapefile> <Output>".format(sys.argv[0]))
  sys.exit(-1)
shapefile_name = sys.argv[1]
outputfile     = sys.argv[2]
polys  = shapefile.Reader(shapefile_name)
shapes = polys.shapes()
cmap   = get_cmap(len(shapes))
#Enable to randomize colours
#random.shuffle(shapes)
fig = plt.figure()
ax  = fig.add_axes((0,0,1,1)) 
for i,poly in enumerate(shapes):
  poly  = poly.__geo_interface__
  color = cmap(i)
  ax.add_patch(PolygonPatch(poly, fc=None, ec="black", alpha=1, zorder=2))
ax.axis('scaled')
ax.set_axis_off()
plt.savefig(outputfile, bbox_inches='tight', pad_inches=0)