Basic Raster Operations
arcgissamples\raster\BasicOperations.java
/* Copyright 2010 ESRI
* 
* All rights reserved under the copyright laws of the United States
* and applicable international laws, treaties, and conventions.
* 
* You may freely redistribute and use this sample code, with or
* without modification, provided you include the original copyright
* notice and use restrictions.
* 
* See the use restrictions.
* 
*/
/*
 * Copyright (c) 2009 ESRI All rights reserved under the copyright laws of the United States and applicable
 * international laws, treaties, and conventions. You may freely redistribute and use this sample code, with or without
 * modification, provided you include the original copyright notice and use restrictions. See use restrictions at
 * /arcgis/java/samples/userestrictions.
 */
/*
 * This example demonstrates basic raster operations such as creation, opening, renaming and deleting
 */

package arcgissamples.raster;

import java.io.File;
import java.io.IOException;

import com.esri.arcgis.datasourcesraster.*;
import com.esri.arcgis.geodatabase.IPixelBlockProxy;
import com.esri.arcgis.geodatabase.IRaster;
import com.esri.arcgis.geodatabase.IRasterDataset;
import com.esri.arcgis.geodatabase.Pnt;
import com.esri.arcgis.geodatabase.rstPixelType;
import com.esri.arcgis.geometry.*;
import com.esri.arcgis.interop.Cleaner;
import com.esri.arcgis.system.*;

public class BasicOperations
{
  public BasicOperations()
  {
    
  }
  
  public static void main(String[] args)
  {
    System.out.println("Starting BasicOperations - An ArcObjects Java SDK Developer Sample");

    try
    {
      // Initialize the engine and licenses.
      EngineInitializer.initializeEngine();

      AoInitialize aoInit = new AoInitialize();
      initializeArcGISLicenses(aoInit);
      
      BasicOperations basicOperations = new BasicOperations();
      basicOperations.runBasicOperations();

      aoInit.shutdown();
    }
    catch(Exception e)
    {
      e.printStackTrace();
    }
  }
  
  /**
   * Run basic raster operations
   * @throws Exception
   */
  public void runBasicOperations() throws Exception
  {
    String fileName = "sampleR";
    String outputPath = getOutputDir();
    
    //create a raster dataset
    RasterDataset rds = createRasterDataset(outputPath, fileName);
    
    //if you'd like to open an existing raster dataset
    //openRasterDataset(outputWorkspace, fileName);
    
    //rename raster dataset
    String newName = "sampleR2";
    rename(rds, newName);    
    
    //reproject raster
    reprojectRasterDataset(rds, 2148);//NAD_1983_CSRS_UTM_Zone_21N

    //delete the raster dataset
    delete(rds);
    
    System.out.println("Done.");    
  }

  /**
   * This example creates a raster dataset with a specified dimension, populates pixel values, 
   * and set a NoData value.  
   * @param path
   * @param fileName
   * @return
   * @throws Exception
   */
  @SuppressWarnings("all")
  public RasterDataset createRasterDataset(String path, String fileName) throws Exception
  {
    System.out.println("\nCreating new raster dataset...");
    //This function opens a raster workspace.
    RasterWorkspaceFactory rasterWSFactory = new RasterWorkspaceFactory();
    RasterWorkspace rasterWS = new RasterWorkspace(rasterWSFactory.openFromFile(path, 0));  
    
    //Define the spatial reference of the raster dataset.
    UnknownCoordinateSystem sr = new UnknownCoordinateSystem();
    
    //Define the origin for the raster dataset, which is the lower left corner of the raster.
    Point origin = new Point();
    origin.putCoords(15.0, 15.0);
    
    //Define the dimension of the raster dataset.
    int width = 100; //This is the width of the raster dataset.
    int height = 100; //This is the height of the raster dataset.
    double xCell = 30; //This is the cell size in x direction.
    double yCell = 30; //This is the cell size in y direction.
    int NumBand = 1; // This is the number of bands the raster dataset contains.
    
    //Create a raster dataset in grid format.
    IRasterDataset rasterDataset = rasterWS.createRasterDataset(fileName, "GRID", origin, width, height, xCell, yCell, NumBand, rstPixelType.PT_UCHAR, sr,
      true);
    
    //Get the raster band.
    IRasterBandCollection rasterBands = (IRasterBandCollection)(rasterDataset);
    IRasterBand rasterBand;
    IRasterProps rasterProps;
    rasterBand = rasterBands.item(0);
    rasterProps = new IRasterPropsProxy(rasterBand);
    
    //Set NoData if necessary. For a multiband image, NoData value needs to be set for each band.
    rasterProps.setNoDataValue(255);
    
    //Create a raster from the dataset.
    IRaster raster = rasterDataset.createDefaultRaster();
    
    //Create a pixel block.
    Pnt blocksize = new Pnt();
    blocksize.setCoords(width, height);
    PixelBlock pixelblock = new PixelBlock(raster.createPixelBlock(blocksize));

    //Populate some pixel values to the pixel block.
    int[][] pixels = (int[][])pixelblock.getPixelData(0);
    for (int i = 0; i < width; i++)
    {
      for (int j = 0; j < height; j++)
      {
        if (i == j)
          pixels[i][j] = (byte)255;
        else
          pixels[i][j] = (byte)((i * j) % 255);
      }
    }

    pixelblock.setPixelData(0, pixels);

    //Define the location that the upper left corner of the pixel block is to write.
    Pnt upperLeft = new Pnt();
    upperLeft.setCoords(0, 0);

    //Write the pixel block.
    IRasterEdit rasterEdit = new IRasterEditProxy(raster);
    rasterEdit.write(upperLeft, new IPixelBlockProxy(pixelblock));

    //Release rasterEdit explicitly.
    Cleaner.release(raster);
    
    System.out.println("Raster dataset " + fileName + " created.");
    
    //return the dataset
    return (RasterDataset) rasterDataset;
  }  
  
  /**
   * Opens a Raster Dataset from disk.
   * 
   * @param directoryName
   *            directory containing the raster file
   * @param fileName
   *            the name of the file to open. If this is an image file, you must include the extension, such as .tif
   *            or .jpg
   * @return
   */
  public RasterDataset openRasterDataset(String path, String fileName)
  {
    RasterDataset rasterDataset = null;
    try
    {
      // Create a workspace factory which then opens a RasterWorkspace and open the dataset
      RasterWorkspaceFactory rasterWorkspaceFactory = new RasterWorkspaceFactory();
      RasterWorkspace rasterWorkspace = (RasterWorkspace) rasterWorkspaceFactory.openFromFile(path, 0);
      rasterDataset = (RasterDataset) rasterWorkspace.openRasterDataset(fileName);
    }
    catch (Exception e)
    {
      System.out.println("Threw an exception trying to open a rasterdataset.");
      e.printStackTrace();
    }

    return rasterDataset;
  }

  /**
   * Re=projects raster dataset using specified Well known ID of a PCS
   * @param rasterDataset
   * @param pcsId
   * @throws IOException
   */
  @SuppressWarnings("all")
  public void reprojectRasterDataset(RasterDataset rasterDataset, int pcsId) throws IOException
  {
    System.out.println("\nRe-projecting raster...");
    Raster raster = new Raster(rasterDataset.createDefaultRaster());
    
    System.out.println("\nCurrent Raster info:" + 
        "\nCoordinate System: " + raster.getSpatialReference().getName() + 
        "\nHeight: " + raster.getHeight() + 
        "\nWidth: " + raster.getWidth() + 
        "\nNumber of Bands: " + raster.getCount() + 
        "\nPixel Type: " + raster.getPixelType());    

    /* set raster property */
    raster.setHeight(raster.getHeight() / 2);
    raster.setWidth(raster.getWidth() / 2);

    /* define new spatial reference */
    SpatialReferenceEnvironment srEnv = new SpatialReferenceEnvironment();
    ISpatialReference prj = srEnv.createProjectedCoordinateSystem(pcsId);    
    
    raster.setSpatialReference(prj);

    System.out.println("\nRe-projected Raster info:" + 
        "\nCoordinate System: " + raster.getSpatialReference().getName() + 
        "\nHeight: " + raster.getHeight() + 
        "\nWidth: " + raster.getWidth() + 
        "\nNumber of Bands: " + raster.getCount() + 
        "\nPixel Type: " + raster.getPixelType());
    
    System.out.println("Done.");
  }
  
  /**
   * Renames specified raster dataset
   * @param rasterDataset
   * @param newName
   * @throws IOException
   */
  private void rename(RasterDataset rasterDataset, String newName) throws IOException
  {
    System.out.println("\nRenaming raster dataset...");
    String oldName = rasterDataset.getName();
    if (rasterDataset.canRename())
    {
      System.out.println("Original Raster Name: " + oldName);
      rasterDataset.rename(newName);        
      System.out.println("New Raster Name: " + rasterDataset.getName());
    }
    else
    {
      System.out.println("Renaming disallowed.");
    }
    System.out.println("Raster dataset " + oldName + " renamed to " + newName + ".");
  }

  /**
   * Deletes specified raster dataset
   * @param rasterDataset
   * @throws IOException
   */
  private void delete(RasterDataset rasterDataset) throws IOException
  {
    String name = rasterDataset.getName();
    System.out.println("\nDeleting Raster Dataset " + name + "...");
    if(rasterDataset.canDelete())
    {
      rasterDataset.delete();
    }
    else
    {
      System.out.println("Unable to delete raster dataset " + name + ".");
    }
    System.out.println("Raster dataset " + name + " deleted.");
  }  
  
  /**
   * Initializes the lowest available ArcGIS License
   */
  static void initializeArcGISLicenses(AoInitialize ao) {
    try {
      
      if (ao.isProductCodeAvailable(com.esri.arcgis.system.esriLicenseProductCode.esriLicenseProductCodeEngine) == com.esri.arcgis.system.esriLicenseStatus.esriLicenseAvailable)
        ao.initialize(com.esri.arcgis.system.esriLicenseProductCode.esriLicenseProductCodeEngine);
      else if (ao.isProductCodeAvailable(com.esri.arcgis.system.esriLicenseProductCode.esriLicenseProductCodeArcView) == com.esri.arcgis.system.esriLicenseStatus.esriLicenseAvailable)
        ao.initialize(com.esri.arcgis.system.esriLicenseProductCode.esriLicenseProductCodeArcView);
      else if (ao.isProductCodeAvailable(com.esri.arcgis.system.esriLicenseProductCode.esriLicenseProductCodeArcEditor) == com.esri.arcgis.system.esriLicenseStatus.esriLicenseAvailable)
        ao.initialize(com.esri.arcgis.system.esriLicenseProductCode.esriLicenseProductCodeArcEditor);
      else if (ao.isProductCodeAvailable(com.esri.arcgis.system.esriLicenseProductCode.esriLicenseProductCodeArcInfo) == com.esri.arcgis.system.esriLicenseStatus.esriLicenseAvailable)
        ao.initialize(com.esri.arcgis.system.esriLicenseProductCode.esriLicenseProductCodeArcInfo);
      else
      {
        System.err.println("Could not initialize an Engine, ArcView, ArcEditor, or ArcInfo license. Exiting application.");
        System.exit(-1);
      }  
      ao.checkOutExtension(com.esri.arcgis.system.esriLicenseExtensionCode.esriLicenseExtensionCodeSpatialAnalyst);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  
  /**
   * Retrieves output directory
   * @return
   */
  private static String getOutputDir()
  {
    String userDir;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") > -1)
    {
      userDir = System.getenv("UserProfile");
    }
    else
    {
      userDir = System.getenv("HOME");
    }
    String outputDir = userDir + "/arcgis_sample_output";
    System.out.println("Creating output directory - " + outputDir);
    new File(outputDir).mkdir();
    return outputDir;
  }
  
}