Select to view content in your preferred language

export each polygone shape to jpeg on a loop with each worldfile using python or arcpy

5160
3
07-31-2014 08:45 PM
MarkDunn
New Contributor

I'm new to Python and Arcpy mapping.  Has anyone built any code for exporting a layer of polygons one record at a time,  I want to select each record,  Zoom to selected and then export each view from the dataframe to jpeg with the worldfile.  I want to name the files with the name of the polygone that is stored in the field name.

 

This is the start of my code.  I'm stuck on selecting each record in a loop and then exporting to jpeg from the datafram not the layout view.  I need to store the worrld file with each export.

 

import arcpy

mxd = arcpy.mapping.MapDocument("CURRENT")

df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]

for row in arcpy.SearchCursor (r"C:\GIS\Grid.shp"):

    df.extent = row.Shape.extent

    df.scale = df.scale *1.07

    arcpy.mapping.ExportToJPEG(mxd, r"C:\GIS\OutputPages\Grid_name.jpg", df,

                           df_export_width=1600,

                           df_export_height=1200,

                           world_file=True)

0 Kudos
3 Replies
MarkDunn
New Contributor

I actually found someone elses code that worked.  How to I change this to make the file name the name of each polygon.  It's stored in the attribute table.

import arcpy
from arcpy import env
from arcpy import mapping
env.workspace = "CURRENT"


mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
for lyr in arcpy.mapping.ListLayers(mxd):
    lyr.visible = True
    fc = r"C:\GIS\Grid.shp"
    count = str(arcpy.GetCount_management(fc))
    x = 0
    while x < int(count) + 1:
        rows = arcpy.SearchCursor(fc, "FID = " + str(x))
        arcpy.SelectLayerByAttribute_management(lyr, "NEW_SELECTION", "FID = " + str(x))

        for row in rows:
            df.zoomToSelectedFeatures()
            df.extent = lyr.getSelectedExtent()
            arcpy.RefreshActiveView()
            mapping.ExportToJPEG(mxd, r"C:\Temp\Map_" + str(x) + ".jpg", df, df_export_width=3004, df_export_height=2125, world_file=True)
            print('Exported image',x, 'of', count)
            x += 1
            print("MXD to JPEGs Export successful")
            print("Thank you!")

0 Kudos
RiyasDeen
Regular Contributor

Assuming this code is working, Change this line from

mapping.ExportToJPEG(mxd, r"C:\Temp\Map_" + str(x) + ".jpg", df, df_export_width=3004, df_export_height=2125, world_file=True)

to

mapping.ExportToJPEG(mxd, r"C:\Temp\Map_" + str(row.getValue(<<fieldName>>)) + ".jpg", df, df_export_width=3004, df_export_height=2125, world_file=True)

where <<fieldName>>, is the name of the field which has polygon data.

0 Kudos
XanderBakker
Esri Esteemed Contributor

Hi Mark,

I have some observations on the code you posted, since there some potential errors in the code:

  • By using the keyword "CURRENT", the code can only be run inside the MXD (from for instance the Python window) and cannot be used as standalone code.
  • You are setting the workspace as "CURRENT". I don't think this is a keyword that can be used for the "current workspace", but the code does not have any parts that require setting the workspace.
  • You are looping through each layer and actually doing the same thing for each layer. The only thing that is influenced is that each time you move to a lower layer this layer is switched on (if it wasn't in the first place). Is this really what you want?
  • What is really an issue is using a count and setting the whereclause for the searchcursor and the select by attribute, based on the assumption that the FID contains sequential numbers and no gaps. When you edit a featureclass and eliminate a feature and add another the sequence will have a gap. Please be aware of that.
  • In case you have polygons that share boundaries, when exporting the polygon, you will see that polygon next to it if it falls within the exporting extent. This can be prevented setting a definition query.
  • Using a search cursor (and preferably the arcpy.da.SearchCursor) allows you to create a more powerful script that will have less chances to fail.

So based on what I described above I would suggest using code like this:

import arcpy, os

def getLayerOnName(mxd, lyr_name):

    for lyr in arcpy.mapping.ListLayers(mxd):

        if lyr.name.upper() == lyr_name.upper():

            return lyr

            break

# some settings and variables

mxd_path = "CURRENT" # or use a path to the mxd file

df_name = "Layers"

lyr_name = "Grid"

fld_id = "FID" # "Name of the field that has a unique number for the output files"

jpg_folder = r"C:\Temp"

jpg_prefix = "Map_"

show_only_current_polygon = True

mxd = arcpy.mapping.MapDocument(mxd_path)

df = arcpy.mapping.ListDataFrames(mxd, df_name)[0]

lyr = getLayerOnName(mxd, lyr_name)

lyr_ds = lyr.dataSource

# loop through all features

flds = ("SHAPE@", fld_id)

with arcpy.da.SearchCursor(lyr_ds, flds) as curs:

    for row in curs:

        pol_ext = row[0].extent

        pol_id = row[1]

        # set a whereclause

        if show_only_current_polygon:

            wc = "{0} = {1}".format(arcpy.AddFieldDelimiters(lyr_ds, fld_id), pol_id)

            lyr.definitionQuery = wc

        df.extent = pol_ext

        jpg_name = "{0}{1}.jpg".format(jpg_prefix, pol_id)

        jpg_path = os.path.join(jpg_folder, jpg_name)

        arcpy.mapping.ExportToJPEG(mxd, jpg_path, df, df_export_width=3004,

                                   df_export_height=2125, world_file=True)

        print "Exported: {0}".format(jpg_name)

What happens in this code is:

  • Lines 3 - 7 defines a function that returns the layer you're interested in based on the name of the layer (as displayed in the TOC)
  • Lines 10 - 16 are used to define some settings (names of mxd, layer, dataframe, output folder, prefix for the jpg and to define if the current polygon is the only polygon that should be showed (for that layer)
  • Lines 18 - 21 reads the mxd, the dataframe the layer and reads the datasource of the layer (you could use the layer itself for the search cursor, but if not all the features are displayed {e.g. a definition query is set} this will affect the number of features processed)
  • Line 24 - 26 the search cursor is defined and the loop is started
  • Line 27 and 28 read the extent of the polygon and the unique id for that polygon
  • Line 31 - 33 will set the definition query to only show the current polygon (if show_only_current_polygon is set to True)
  • Line 35 sets the extent of the dataframe
  • Line 36 - 37 defines the output file name
  • Line 38 - 39 exports the jpg
  • Line 41 prints the process

Give it a shot and see if it works...

Kind regards, Xander