使用Arcpy的mapping工具批量导出tif图片,将多个图层文件批量导出为jpg,需要根据需要提前设置样式模板、布局视图、图例等。根据图层名称批量修改图片标题、导出图片文件名。
1、在mxd文档中,插入文本框并命名
2、通过 arcpy.mapping.ListLayoutElements 工具获取文本框信息
通过name定位,需要知道想更改的文本框名称。
layouts= arcpy.mapping.ListLayoutElements(mxd, 'TEXT_ELEMENT')
for layout in layouts:
if layout.name == 'Iwant':
text_element = layout
!!!不知道为什么,我改了名称,却取不到这个名称,可能是ARCMAP软件语言的缘故?所以我是用index定位的。
通过index定位,需要知道想更改的文本框序号。
text_element = arcpy.mapping.ListLayoutElements(mxd, 'TEXT_ELEMENT')[2]
3、获取可显示图层
layers = arcpy.mapping.ListLayers(mxd)
4、获取模板图层,需要提前设置好该图层样式,并用此模板修改图层
originLayerName = "model 1.0.tif" # 这里填入设置好的图层样式名称
originLayer = arcpy.mapping.ListLayers(mxd, originLayerName)[0]
# 修改图层样式
if (originLayer.isFeatureLayer and lyr.isFeatureLayer) or (originLayer.isRasterLayer and lyr.isRasterLayer):
arcpy.ApplySymbologyFromLayer_management(in_layer=lyr, in_symbology_layer=originLayer)
5、根据图层名称,修改布局显示文本标题信息
# text_element.text = 'what you want'
text_element.text = '2007'+lyr.name.split('.')[0].split('_')[1]+' MODIS'
6、根据需求打开或关闭图层,并打印
lyr.visible = True
arcpy.mapping.ExportToJPEG(mxd, jpg_file.format(text_element.text), resolution=res)
lyr.visible = False
7、根据需求可选保存修改,释放当前mxd
mxd.save()
del mxd
完整代码如下:
def modis_to_jpg(mxd_file, jpg_file):
res = arcpy.GetParameterAsText(2) # 分辨率
mxd = arcpy.mapping.MapDocument(mxd_file)
text_element = arcpy.mapping.ListLayoutElements(mxd, 'TEXT_ELEMENT')[2]
# print text_element.text
originLayerName = "model 1.0.tif" # 这里填入设置好的图层样式名称
try:
originLayer = arcpy.mapping.ListLayers(mxd, originLayerName)[0]
except:
pass
layers = arcpy.mapping.ListLayers(mxd)
for lyr in layers:
if lyr.name in ['province', 'model 1.0.tif', 'model 1.5.tif']:
continue
print lyr.name
text_element.text = '2007'+lyr.name.split('.')[0].split('_')[1]+' MODIS'
try:
if (originLayer.isFeatureLayer and lyr.isFeatureLayer) or (originLayer.isRasterLayer and lyr.isRasterLayer):
arcpy.ApplySymbologyFromLayer_management(in_layer=lyr, in_symbology_layer=originLayer)
except:
pass
lyr.visible = True
arcpy.mapping.ExportToJPEG(mxd, jpg_file.format(text_element.text), resolution=res)
lyr.visible = False
print 'done'
mxd.save()
del mxd