Zoom to tile and Export to JPEG with World File

4663
3
Jump to solution
08-23-2012 07:13 PM
Thiru_P
Occasional Contributor
Hi,

I would like to zoom to features and export the map data frame into JPEGs with world files.

I have created an Index Grid shapefile that covers my area of interest. All I need to to is go through each row/record in the shapefile, zoom to extent and export the data frame as JPEG with worldfile.

I am new to python programming. I have composed a python script (thanks to fellow members), but it is not working.


import arcpy from arcpy import env from arcpy import mapping env.workspace = r"C:\temp\python"  mxd = mapping.MapDocument(r"C:\Temp\Sample.mxd") df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]  for lyr in arcpy.mapping.ListLayers(mxd):     lyr.visible = True fc = r"C:\Temp\Grid.shp" count = str(arcpy.GetCount_management(fc)) x = 0 while x < int(count) + 1:     rows = arcpy.SearchCursor(fc, "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!")








I would really appreciate your help in correcting this.
0 Kudos
1 Solution

Accepted Solutions
JeffBarrette
Esri Regular Contributor
The easiest thing to correct is the fact that you are not selecting anything so I'll bet all your output files were identical.  I added the arcpy.SelectLayerByAttribute function.  But then you should also clear the selection so you don't see the selected feature in the output, etc.

import arcpy from arcpy import env from arcpy import mapping env.workspace = r"C:\temp"    ###modified this too because I put the shapefile and MXD in the same folder called temp  mxd = mapping.MapDocument(r"C:\Temp\Sample.mxd") df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0] for lyr in arcpy.mapping.ListLayers(mxd):     lyr.visible = True fc = r"C:\Temp\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))   ######Added this line     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!")


I personally whould have tried a different approach (without the while loop).  Here is a very simple and direct solution:

import arcpy mxd = arcpy.mapping.MapDocument(r"C:\Temp\Sample.mxd") df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]  lyr = arcpy.mapping.ListLayers(mxd, "grid")[0]  ##shapefile layer name called grid rows = arcpy.SearchCursor(lyr)  x=1 for row in rows:   df.extent = row.Shape.extent   arcpy.mapping.ExportToJPEG(mxd, r"C:\Temp\Map_" + str(x) + ".jpg", df, df_export_width=3004, df_export_height=2125, world_file=True)   print x   x+=1


I hope this helps,
Jeff

View solution in original post

0 Kudos
3 Replies
JeffBarrette
Esri Regular Contributor
The easiest thing to correct is the fact that you are not selecting anything so I'll bet all your output files were identical.  I added the arcpy.SelectLayerByAttribute function.  But then you should also clear the selection so you don't see the selected feature in the output, etc.

import arcpy from arcpy import env from arcpy import mapping env.workspace = r"C:\temp"    ###modified this too because I put the shapefile and MXD in the same folder called temp  mxd = mapping.MapDocument(r"C:\Temp\Sample.mxd") df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0] for lyr in arcpy.mapping.ListLayers(mxd):     lyr.visible = True fc = r"C:\Temp\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))   ######Added this line     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!")


I personally whould have tried a different approach (without the while loop).  Here is a very simple and direct solution:

import arcpy mxd = arcpy.mapping.MapDocument(r"C:\Temp\Sample.mxd") df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]  lyr = arcpy.mapping.ListLayers(mxd, "grid")[0]  ##shapefile layer name called grid rows = arcpy.SearchCursor(lyr)  x=1 for row in rows:   df.extent = row.Shape.extent   arcpy.mapping.ExportToJPEG(mxd, r"C:\Temp\Map_" + str(x) + ".jpg", df, df_export_width=3004, df_export_height=2125, world_file=True)   print x   x+=1


I hope this helps,
Jeff
0 Kudos
BrandonVan_Horn
Occasional Contributor
Thanks for posting this code. It helped me develop my own. This allows you to adjust the resolution, and the width of the exported image. It also allows you to print specific pages. Just figured I would post it for someone else's use. Have a great day!
 import arcpy, os, exceptions, collections
print "Starting process " + str(time.ctime())
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]
mapLayers = arcpy.mapping.ListLayers(mxd)
out_loc = "\\\\ntdmzgis\\Data\\NameOfFolderHere\\" #TODO: Set the output locations, add as a parameter
res = 300 #TODO: this is the output resolution 300
dfWidth = 8 #TODO: this is the width of the dataframe in inches
inch_to_meters = 0.0254 #This is the convertion for inches to meters must match the defined coordinate system of the data frame
print_pages = [] #TODO: Add pages; example range ['6-8',21,'9-18',36], leave blank to get all pages
if mapLayers.count <> 0:
    for lyr in arcpy.mapping.ListLayers(mxd, "L*", df): #This selects the layer names,make sure they are named L1, L2, etc. Can manually select layer if needed 
        print "Checking if " + lyr.name + " is feature Layer"
        if lyr.isFeatureLayer == True: 
            print "We found a feature layer"
            if os.path.exists(out_loc + lyr.name):
                #print "Folder existed" #Uncomment this line and Comment out next line if you want to overwrite the folder
                raise Exception ("This " + out_loc + lyr.name + " folder existed! \n Are you sure this is the right location? \n  Yes, Please move, rename, or delete to continue...")
            else:
                os.makedirs(out_loc + lyr.name)
                print "A new directory was made at " + out_loc + lyr.name
            rows = arcpy.SearchCursor(lyr) 
            print "Starting process to make clipped JPEGs for " + lyr.name + "  " + str(time.ctime())
            d = len(print_pages)
            if d <= 0:
                rows1 = arcpy.SearchCursor(lyr)
                for rw in rows1:
                    print_pages.append(rw.getValue("PageNumber"))
            if [el for el in print_pages if isinstance(el, collections.Iterable) and ('-' in el)]:
                print "We have a range"
                for p in range(d):
                    print str(p) + " of " + str(d)
                    if  print_pages
.find("-"):
                        l = print_pages

                        m = l.partition("-")[0]
                        n = l.partition("-")[2]
                        del print_pages
 
                        for o in range(int(m),int(n)+1):
                            print_pages.append(o)
                        del l, m, n, o 
            else:
                print "No range selected"
            print print_pages
            for row in rows:
                pg = row.getValue("PageNumber")
                if pg in print_pages:  
                    df.extent = row.Shape.extent
                    print "Feature Extent: " + str(row.Shape.extent)
                    print "Selected scale: " + str(df.scale) 
                    xmin, ymin, xmax, ymax = row.shape.extent.XMin, row.shape.extent.YMin, row.shape.extent.XMax, row.shape.extent.YMax
                    xWidth = xmax - xmin
                    yHeight = ymax - ymin
                    featSq = math.sqrt(math.pow(xWidth,2) + math.pow(yHeight,2))
                    dfSq = math.sqrt(math.pow(df.elementWidth * inch_to_meters,2) + math.pow(df.elementHeight * inch_to_meters,2))
                    #Calculates the needed scale to fit image into dataframe size
                    if mxd.activeView != 'PAGE_LAYOUT' :
                        df.scale =  (featSq / dfSq) * 0.651951975
                    else:
                        df.scale =  (featSq / dfSq)
                    print "Using scale for " + mxd.activeView
                    print "Adj. scale: " + str(df.scale) 
                    #Set the size of the dataframe to match the feature
                    df.elementWidth = dfWidth
                    df.elementHeight = dfWidth * (yHeight/xWidth)
                    df.elementPositionX, df.elementPositionY = 0, 0
                    print "DF Width: " +str(df.elementWidth) + " x Height: " + str(df.elementHeight)                    
                    #Set the pixel size based on the resolution
                    df = arcpy.mapping.ListDataFrames(mxd)[0]
                    picWidth = long(df.elementWidth * res)
                    picHeight = long(df.elementHeight * res)
                    print "Image Width: " +str(picWidth) + " x Height: " + str(picHeight)                    
                    print "Working on row..." + str(row.getValue("PageNumber")) + " at " + str(time.ctime())
                    arcpy.RefreshActiveView()
                    arcpy.mapping.ExportToJPEG(mxd, out_loc + lyr.name + "\\" + str(row.getValue("PageNumber")) + ".jpg", df, df_export_width= picWidth, df_export_height=picHeight, resolution=res, world_file=True)
                    print "Finished row..." + str(row.getValue("PageNumber")) + " at " + str(time.ctime())
            print lyr.name + " JPEGs have been made at " + str(time.ctime())
        else:
            print lyr.name + " was not a Feature Class"
    try:
        lyr
    except:
        del mxd, df, mapLayers, out_loc, res, dfWidth, inch_to_meters
        raise Exception ("Check the layer Name in line 12 is actually in the map.")
else:
    raise Exception ("No layers were in map.")
print "Creating web cache completed " + str(time.ctime())
#clean up our varibles
del mxd, df, mapLayers, out_loc, res, dfWidth, inch_to_meters, lyr, rows, row, print_pages, xmin, ymin, xmax, ymax, xWidth, yHeight, featSq, dfSq, picWidth, picHeight, p,rows1, rw 
 
AlbertoUtreras
New Contributor
Hello,
  I have seen the Python code, and apparently is what I searched for some applications in my daily work.

I understand that the code performs image capture and export to a jpg file, in this case with 300 dpi resolution.

I perform this task manually and it is too tedious.
  But apparently this way .... the problem is nothing Python ... can help me get this running on my PC ..... work in ArcGIS 10 ...
  I loaded the module Pyscriber Python 2.7 ... but still do not understand some things ....

It is possible your support for the successful implementation ....

Some other questions:

Is this possible run in batch mode? from a reference shape or feature ....

Can I choose the scale deployment at will?

Can I control the display time of the image?, Ie waiting for an image to load.

I appreciate your response .... I hope progress in Python.

regards

Alberto

Note: sorry for my English , is another thing I must acquire
0 Kudos