TIFF_TO_JP2_Pipeline.sml

  Download

More scripts: Import & Export

Syntax Highlighing:

comments, key words, predefined symbols, class members & methods, functions & classes
            
# TIFF_TO_JP2_Pipeline.sml
# Sample script for tutorial Writing Scripts with SML
# Links to one or more input GeoTIFF files and exports each to a GeoJP2 file
# with selected compression settings.  GeoTIFF files may contain composite
#  or separate bands. Script creates a custom dialog window to manage user inputs.
# version 29 May 2014. 
#################  Global Variables  #########################
class STRING outputDir$;					# path to output directory
class STRINGLIST filepathlist;			# list of filepaths of the TIFF files selected
numeric numfiles; 							# number of TIFF files selected
numeric err;									# value returned for error checking
class GUI_DLG dlgwin;						# the dialog window created by script
class GUI_CTRL_LISTBOX filelistbox;		# handle for file listbox on the dialog
class GUI_CTRL_PUSHBUTTON dirBtn, runBtn;	# handles for pushbuttons
numeric ratioEnabled = 1;		# flag for tracking whether compression ratio field has been enabled
class RVC_OBJITEM objItemList[]; # hash of objItems for the component rasters to be created
																				# from a single multiband GeoTIFF file
#################  User-Defined Procedures  ##########################
# error checking procedure
proc ReportError(numeric linenum, numeric err) {
	printf("FAILED -line: %d, error: %d\n", linenum, err);
	PopupError(err); 
	}
# procedure called when the dialog window opens; use to get class handles for controls
proc OnOpen()
	{
	filelistbox = dlgwin.GetCtrlByID("filelistbox");
	dirBtn = dlgwin.GetCtrlByID("dirBtn");
	runBtn = dlgwin.GetCtrlByID("runBtn");
	}
# Procedure called by the Select TIFF Files button on the dialog.
# Gets a stringlist with the filepath strings for the selected files, 
# writes the filepath strings to the file listbox on the dialog, and
# enables the Get Directory button
proc GetInputFiles() 
	{
	local numeric i;
	dlgwin.SetCtrlValueStr("msgText", "");
	# clear previous input file list if any
	if (filepathlist.GetNumItems() > 0 ) then filepathlist.Clear();
	if (filelistbox.GetCount() > 0 ) then filelistbox.DeleteAllItems();
	# get input GeoTIFF files
	numfiles = GetInputFileNames(_context.ScriptDir, "Select TIFF file(s) for conversion to JP2:", "tif", filepathlist);
	printf("numfiles = %d\n", numfiles);
	for i = 1 to numfiles
		{
		filelistbox.AddItem( filepathlist[i-1] );			# add filepath string to the listbox
		}
	dirBtn.SetEnabled(1);		# enable the button to select output directory
	# if an output directory has already been selected in a previous run, enable the Run button
	if (outputDir$ <> "") then runBtn.SetEnabled(1);
	}
# Procedure called by the Select Output Directory button on the dialog
# Gets the output directory path and enables the Run Jobs and Save Jobs buttons
proc GetOutputDirectory()
	{
	outputDir$ = GetDirectory("", "Choose directory for JP2 files:");
	if (outputDir$ == "") then
		PopupMessage("No directory selected.  Please choose an output directory.");
	else {
		outputDir$ = outputDir$ + "/";
		dlgwin.SetCtrlValueStr("outDirText", outputDir$);		# write directory name to the dialog
		runBtn.SetEnabled(1);			# enable the Run button
		}
	}
# procedure called by the Close button on the dialog
proc OnClose()
	{
	dlgwin.Close(0);
	Exit();
	}
# Procedure called when JPEG2000 compression option is selected.
# Changes the state of associated controls on the dialog
proc OnCompSelected()
	{
	if (dlgwin.GetCtrlByID("jp2compOptions").GetValueStr() == "LossyRatio")		# user-defined compression is set
		{
		if (ratioEnabled <> 1)		# if ratio label and field are currently disabled, enable them
			{
			dlgwin.GetCtrlByID("ratioLabel").SetEnabled(1);
			dlgwin.GetCtrlByID("compRatioNum").SetEnabled(1);
			ratioEnabled = 1;
			}
		}
	else		#  compression option = lossless or best quality
		{
		if (ratioEnabled == 1)		# if ratio label and field are enabled, disable them
			{
			dlgwin.GetCtrlByID("ratioLabel").SetEnabled(0);
			dlgwin.GetCtrlByID("compRatioNum").SetEnabled(0);
			ratioEnabled = 0;
			}
		}
	}
# Procedure called by the Run icon button
proc OnRun()
	{
	local numeric i, j;				# loop counters
	local string inputPath$;		# string with the filepath of the current input TIFF file
	local string compType$;			# type of JPEG2000 compression to set
	local numeric compRatio;		# target compression ratio for lossy compression
	local class STRING dest$;			# string with destination path and filename
	local numeric err;
	# get compression options from the dialog
	compType$ = dlgwin.GetCtrlValueStr("jp2compOptions");
	if (compType$ == "LossyRatio") 			# get target ratio for user-defined compression
		{
		compRatio = dlgwin.GetCtrlValueNum("compRatioNum");
		printf("compression ratio = %d", compRatio);
		}
	else
		compRatio = 0;
	# loop through selected input GeoTIFF files
	for i = 1 to numfiles
		{
		# get path string for current GeoTIFF file
		inputPath$ = filepathlist[ i - 1 ];
		local class FILEPATH inFilepath(inputPath$);
		# PIPELINE SOURCE for the GeoTIFF file
		local class IMAGE_PIPELINE_SOURCE_TIFF sourceGeoTIFF(inFilepath);
		err = sourceGeoTIFF.Initialize();
		if (err < 0) 
			ReportError(_context.CurrentLineNum, err);
		else
			print("Pipeline source intialized.");
		# SETTINGS FOR THE J2K TARGET
		local class IMAGE_PIPELINE_TARGET_J2K_SETTINGS settingsJ2K;		
		settingsJ2K.SetGeoMethod("GeoTIFF");
		if (compType$ == "Lossless")
			{ 
			settingsJ2K.SetReversible(1);
			print("Set Lossless");
			}
		else if (compType$ == "LossyRatio")
			{
			settingsJ2K.SetReversible(0); 
			settingsJ2K.SetTargetRatio(compRatio);
			print("Set Ratio");
			}
		else if (compType$ == "LossyBest")
			{
			settingsJ2K.SetReversible(0);  
			settingsJ2K.SetTargetQuality(100);
			print("Set LossyBest");
			}		
		# Create filepath for the output GeoJP2 file
		local class STRING filename$ = inFilepath.GetNameOnly();	# name of current input GeoTIFF file 
		dest$ = outputDir$ + filename$ + ".jp2";
		local class FILEPATH j2kFilepath(dest$);
		# PIPELINE TARGET for the GeoJP2 file			
		local class IMAGE_PIPELINE_TARGET_J2K targetJ2K(sourceGeoTIFF, j2kFilepath, settingsJ2K, "none");
		err = targetJ2K.Initialize();
		if (err < 0) 
			ReportError(_context.CurrentLineNum, err);
		else
			print("Pipeline target initialized.");
		# EXECUTE PIPELINE 
		targetJ2K.Process();
		}
	dlgwin.SetCtrlValueStr("msgText", "Done.");
	}	# end OnRun()
#########################   Main Program  ###################################
clear();
# dialog specification
class STRING xml$ = '<?xml version="1.0"?>
	<!DOCTYPE root SYSTEM "smlforms.dtd">
	<root>
		<dialog id="dlg" Title="TIFF to JP2 Conversion" Buttons="" OnOpen="OnOpen()">
			<pushbutton Name=" Select TIFF Files " OnPressed="GetInputFiles()"/>
			<listbox id="filelistbox" Width="40" />
			<pushbutton id="dirBtn" Name=" Select Output Directory " Enabled="false" OnPressed="GetOutputDirectory()"/>
			<edittext id="outDirText" ReadOnly="true" Width="40"/>
			<pane Orientation="horizontal" HorizResize="Fixed">
				<label>JPEG2000 compression</label>
				<combobox id="jp2compOptions" Default="LossyRatio" OnSelection="OnCompSelected()">
					<item Name="Lossless" Value="Lossless"/>
					<item Name="Best Quality" Value="LossyBest"/>
					<item Name="User Defined" Value="LossyRatio"/>
				</combobox>
				<label id="ratioLabel" Enabled="true">Target ratio</label>
				<editnumber id="compRatioNum" Width="3" Precision="0" Default="15" Enabled="true"/>
			</pane>
			<edittext id="msgText" Width="40" ReadOnly="true"/>
			<pane Orientation="horizontal" HorizResize="Fixed" HorizAlign="Right">
				<pushbutton id="runBtn" Name=" Run " Enabled="false" OnPressed="OnRun()"/>
				<pushbutton Name=" Close " OnPressed="OnClose()"/>
			</pane>
		</dialog>
	</root>';
##############################################
### parse XML text for the dialog into memory; 
### return an error code (number < 0 ) if there are syntax errors
class XMLDOC dlgdoc;
err = dlgdoc.Parse(xml$);
if ( err < 0 ) {
	PopupError( err ); 	# Popup an error dialog. "Details" button shows syntax errors.
	Exit();
	}
################################################
# get the dialog element from the parsed XML document and
# show error message if the dialog element can't be found
class XMLNODE dlgnode;
dlgnode = dlgdoc.GetElementByID("dlg");
if ( dlgnode == 0 ) {
	PopupMessage("Could not find dialog node in XML document");
	Exit();
	}
################################################
# Set the XML dialog element as the source for the GUI_DLG class 
# instance we are using for the dialog window.
err = dlgwin.SetXMLNode(dlgnode);
if ( err < 0 ) {
	PopupError( err ); 	# Popup an error dialog. 
	Exit();
	}
dlgwin.CreateModeless();
dlgwin.Open();
WaitForExit();