Using arcpy.mapping.AddLayer to import raster in RGB instead of single-band stretched symbology

10-09-2018 06:00 AM
Occasional Contributor II

Hi, I am working with a simple script that imports geo-referenced rasters corresponding to selected polygons in a featureclass layer. The rasters import just fine, but the issue is that they import as single band streched rasters and I have to go into the layer symbology tab under properties and then change the imported rasters to RGB composite individually. Does anyone have any idea how I could skip that manual step and code for this to happen automatically? The relevant code snippet looks like this:

  1. #Fetch selected rasters and add to current map document, first data frame  
  2. mxd = arcpy.mapping.MapDocument("CURRENT")  
  3. df = arcpy.mapping.ListDataFrames(mxd, "*")[0]  
  4. arcpy.AddMessage(len(docs))#DEBUG#  
  5. for i, page in enumerate(docs):  
  6.         arcpy.AddMessage(i)  
  7.         newlayer = arcpy.mapping.Layer(page)  
  8.         arcpy.mapping.AddLayer(df,newlayer, "TOP")  

Thank you!

0 Kudos
3 Replies
New Contributor II

To do this you need to first set the RGB composite manually on one raster and save it as a lyr file. You can then use the lyr file to update the symbology of the raster that you have added with arcpy.mapping.Updatelyr. Here is a script that i wrote to add all of the .tif files in a folder to a mxd and set the symbology as RGB. 

#-*- coding: utf-8 -*-
import glob
import os
import arcpy

#Count number of files added to mxd
count = 0

path = r"V:/Path/to/raster/folder"
MXD = r"V:/Path/to/arcmapdocument/mymap.mxd"
sourceLayer = arcpy.mapping.Layer(r"V:/path/to/layerfile/rgb.lyr")

mxd = arcpy.mapping.MapDocument(MXD)
df = arcpy.mapping.ListDataFrames(mxd)[0]

for file in os.listdir(path):
    if file.endswith(".tif"):
        name = file.split('.')[0]
        print name

        rasterPath =os.path.join(path, file)
        updatelyr = arcpy.mapping.Layer(rasterPath)
        arcpy.mapping.UpdateLayer(df, updatelyr, sourceLayer, True)
        arcpy.mapping.AddLayer(df, updatelyr, "BOTTOM")
        count = count + 1

print count

Hope this helps!

Occasional Contributor II

Thank you, this worked!

It's really disappointing that arcpy.mapping doesn't let you edit layer properties directly in script though 😕

0 Kudos
MVP Legendary Contributor

Symbology—ArcPy | ArcGIS Desktop 

mp in ArcGIS Pro, example 2 gives an example or changing a raster's classification field, and color ramp. I doubt that this is new to Pro, so the equivalent might exist in the 'mapping' model

0 Kudos