1. 使用 ListFiles 函数获取需要处理的所有栅格图层的路径名(这些图层必须是 ArcGIS 支持的栅格格式,例如:JPEG、TIFF、PNG 等),然后再遍历图层列表执行操作。示例代码如下:
import arcpy
from arcpy.sa import *
# Set input file path and output folder path
in_path = "D:/path/to/input/folder"
out_folder = "D:/path/to/output/folder"
# Obtain a list of all raster files in the input folder
all_files = arcpy.ListFiles("*", "Raster", in_path)
for in_file in all_files:
# Check whether the raster is a JPEG and is worth processing
if not (in_file.endswith(".jpg") or in_file.endswith(".jpeg")):
continue
# Compose the output file name and path
out_file = in_file[:-4] + ".jpg"
out_path = out_folder + "/" + out_file
# Execute the RasterToOtherFormat_conversion function to convert the input raster to JPEG format
arcpy.RasterToOtherFormat_conversion(in_file, out_path, "JPEG")
2. 如果您还需要针对不同的图层指定不同的输出参数,可以在循环体中添加变量来保存这些自定义配置。例如,如果您有多个输入文件夹和多个输出文件夹,并且需要为每个图层指定输出分辨率和压缩质量,则可以创建一个字典,将输入/输出文件夹和输出参数保存在其中:
import arcpy
from arcpy.sa import *
# Define the input/output file locations and output parameters
file_config = {
"input_folder": "D:/path/to/input/folder",
"output_folder": "D:/path/to/output/folder",
"out_resolution": 200,
"out_quality": 80
}
# Obtain a list of all raster files in the input folder
all_files = arcpy.ListFiles("*", "Raster", file_config["input_folder"])
for in_file in all_files:
# Check whether the raster is worth processing
if not (in_file.endswith(".jpg") or in_file.endswith(".jpeg")):
continue
# Compose the output file name and path
out_file = in_file[:-4] + ".jpg"
out_path = file_config["output_folder"] + "/" + out_file
# Execute the RasterToOtherFormat_conversion function to convert the input raster to JPEG format, using specified output parameters
arcpy.RasterToOtherFormat_conversion(in_file, out_path, "JPEG", "", "", file_config["out_resolution"], "", "", "", "", "", "", file_config["out_quality"])
注意:在执行上述操作时,请确保对应文件的路径和格式信息是否正确,并检查计算机性能和资源使用情况等问题。