# Load GeoJSON and then export it as an image programatically in QGIS with Python?

I have around 6000 geoJson files that I would like to import each, change the feature colors and background color, and export as just images (png/jpeg/etc doesn't matter).

So some pseudocode

for geoJsonFile in geoJsonDir
changeSomeFeatures()
exportAsPNG()


I found the exportAsPNG() but I get an AttributeError that QgsApplication does not have exportItemsPNG()...so I guess it's not actually in the standard API?

Here is my basic code I have right now to try and load one geoJSON and save it...

from qgis.core import *

# create a reference to the QgsApplication, setting the
# second argument to False disables the GUI
qgs = QgsApplication([], False)

qgs.initQgis()

vlayer = QgsVectorLayer("my_geojson.geojson","my_geojson_vector","ogr")
qgs.exportItemsPNG()

qgs.exitQgis()

print("I guess it worked?")

• I'm not sure about the exportAsPNG method. But is there a reason you need to use qgis? Would a solution using the matplotlib/descartes python libraries be acceptable? If you could show your data's schema and explain how you want it styled that would also be helpful. – RoperMaps Jul 5 '17 at 16:00
• Yeah I could use matplotlib as well, doesn't have to be QGIS. Basically I have an map image of an area and the geoJson of the corresponding labelled buildings. I just need the geojson features to be white and the background to be black then export that as an image. I'll look into matplotlib I didn't know it could do that, thanks. – Carson Jul 5 '17 at 16:03
• Haven't had any luck trying to get that to work, closest I've gotten is this example: stackoverflow.com/questions/23081188/… though I get KeyError on 'bounds' – Carson Jul 5 '17 at 17:11

Here is the code I've figured out with QGIS, copy and paste it into the Python console works (while annoying, I wish qgis had a cli). Working on a having it iterate through multiple files now, but wanted to post this here before I forget.

from PyQt4.QtGui import *
from PyQt4.QtCore import *
from qgis.core import *

#Set canvas color to black
iface.mapCanvas().setCanvasColor(QColor.fromRgb(0,0,0))

layer = iface.addVectorLayer("C:\\path\\to\\geojson", "my layer", "ogr")

#Set Symbol color to white
symbols = layer.rendererV2().symbols()
symbol = symbols[0]
symbol.setColor(QColor.fromRgb(255,255,255))

# Save map canvas
iface.mapCanvas().saveAsImage("C:\\path\\to\\destination\\image.png")

#Delete Layer
with edit(layer):
for feat in layer.getFeatures():
layer.deleteFeature(feat.id())