Thursday 30 July 2015

python - Insert Raster to MXD using arcpy.mapping (ArcGIS 10)




What i want to do seems simple. But again i can't even find a workaround...

I have got a lot of Raster-files (ESRI-GRID) which i need to insert into a layout mxd-file and then export the map to PDF/JPEG/whatever.

The Final Export in Python is no Problem.
But how do I insert/replace a Raster in the mxd file?
It has to be something like:


fcs = gp.ListRasters("*", "GRID")
for fc in fcs:
[change Raster (/ Raster Data Source?)]
arcpy.mapping.ExportToPDF(mxd, "D:\\test.pdf")

I Hope that anybody has an idea :)
Thanks for your help!

Markus



Answer



Here is a script that I used for changing all the sources in a map document from an SDE raster catalogs to raster mosaics. This could hopefully be a good lead for what you are trying to do. Notice that I pre-built the .lyr files and stored them in a specific location. You can use artwork21's method to automatically create .lyr files too instead of prebuilding.


import arcpy
path = u'sample' #Our internal path to the mosaic directory. Removed from this sample.
mxd = arcpy.mapping.MapDocument("CURRENT") #You can also have this go to a specific mxd
print "Updating Aerial Catalogs to Aerial Mosaics..."
for df in arcpy.mapping.ListDataFrames(mxd):
for refLayer in arcpy.mapping.ListLayers(mxd, "*.AERIAL_*", df):
year = refLayer.dataSource[-4:] #This is based on our naming convention, AERIAL_YYYY

print u'Updating AERIAL_' + year + u' to Mosaic....
if year == u'1970':
year = u'1970_72'
if year == u'1997':
year = u'1995_97'
name = u'Mosaic_' + year + u'.lyr'
mosaic = arcpy.mapping.Layer(path + name) #Making a new layer
arcpy.mapping.InsertLayer(df, refLayer, mosaic, "BEFORE") #Insert the layer in front of the layer I am replacing
mosaic.visible = refLayer.visible #Copying across all the attributes on the old layer
mosaic.brightness = refLayer.brightness

mosaic.contrast = refLayer.contrast
mosaic.transparency = refLayer.transparency
mosaic.name = refLayer.name
arcpy.mapping.RemoveLayer(df, refLayer) #Take out the old raster layer
print name + u' updated.'
arcpy.RefreshActiveView() #Not needed if you are not working on an open document
arcpy.RefreshTOC() #Not needed if you are not working on an open document
del mxd, df
try:
del refLayer, year, name, path, mosaic #Do your cleanup properly

except:
pass
finally:
print u'All Mosaics updated!'

I have a much more complicated version of this that spiders through a drive and changes -every- mxd on the drive too, if that is needed.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...