IDL-Java Bridge Examples

The following examples demonstrate how to access data through the IDL-Java bridge:

Accessing Arrays Example

This example creates a two-dimensional array within a Java class, which is contained in a file named array2d.java. IDL then accesses this data through the ArrayDemo routine, which is in a file named arraydemo.pro.

Example Code
These files are located in the resource/bridges/import/java/examples directory of the IDL distribution. Run this example procedure by entering arraydemo at the IDL command prompt or view the file in an IDL Editor window by entering.EDIT arraydemo.pro.

The array2d.java file contains the following text for creating a two-dimensional array in Java:

public class array2d { 
   short[][] m_as; 
   long[][] m_aj; 
 
   // ctor 
   public array2d() { 
      int SIZE1 = 3; 
      int SIZE2 = 4; 
 
      // default ctor creates a fixed number of elements 
      m_as = new short[SIZE1][SIZE2]; 
      m_aj = new long[SIZE1][SIZE2]; 
 
      for (int i=0; i<SIZE1; i++) { 
        for (int j=0; j<SIZE2; j++) { 
          m_as[i][j] = (short)(i*10+j); 
          m_aj[i][j] = (long)(i*10+j); 
         } 
      } 
    
 } 
 
   public void setShorts(short[][] _as) { 
      m_as = _as; 
   } 
 
    public short[][] getShorts() {return m_as;} 
 
    public short getShortByIndex(int i, int j) { 
      return m_as[i][j]; 
   } 
 
   public void setLongs(long[][] _aj) { 
      m_aj = _aj; 
   } 
 
   public long[][] getLongs() {return m_aj;} 
   public long getLongByIndex(int i, int j) {return m_aj[i][j];} 
 
} 

The arraydemo.pro file contains the following text for accessing the two-dimensional array within IDL:

PRO ArrayDemo 
 
; The Java class array2d creates 2 initial arrays, one 
; of longs and one of shorts. We can interrogate and 
; change this array. 
oJArr = OBJ_NEW('IDLJavaObject$ARRAY2D', 'array2d') 
 
; First, let's see what is in the short array at index 
; (2,3). 
PRINT, 'array2d short(2, 3) = ', $ 
   oJArr -> GetShortByIndex(2, 3), $ 
   '    (should be 23)' 
 
; Now, let's copy the entire array from Java to IDL. 
shortArrIDL = oJArr->GetShorts() 
HELP, shortArrIDL 
PRINT, 'shortArrIDL[2, 3] = ', shortArrIDL[2, 3], $ 
   '    (should be 23)' 
 
; Let's change this value... 
shortArrIDL[2, 3] = 999 
; ...and copy it back to Java... 
oJArr->SetShorts, shortArrIDL 
; ...now its value should be different. 
PRINT, 'array2d short(2, 3) = ', $ 
   oJArr->GetShortByIndex(2, 3), '    (should be 999)' 
 
; Let's set our array to something different. 
oJArr -> SetShorts, INDGEN(10, 8) 
PRINT, 'array2d short(0, 0) = ', $ 
   oJArr->GetShortByIndex(0, 0), '    (should be 0)' 
PRINT, 'array2d short(1, 0) = ', $ 
   oJArr->GetShortByIndex(1, 0), '    (should be 1)' 
PRINT, 'array2d short(2, 0) = ', $ 
   oJArr->GetShortByIndex(2, 0), '    (should be 2)' 
PRINT, 'array2d short(0, 1) = ', $ 
   oJArr->GetShortByIndex(0, 1), '    (should be 10)' 
 
; Array2d has a setLongs method, but b/c arrays do not 
; (currently) promote, the first call to setLongs works 
; but the second fails. 
oJArr->SetLongs, L64INDGEN(10, 8) 
PRINT, 'array2d long(0, 1) = ', $ 
   oJArr->GetLongByIndex(0, 1), '    (should be 10)' 
 
;PRINT, '(expecting an error on the next line...)' 
;oJArr->SetLongs, INDGEN(10,8) 
 
; Cleanup our object. 
OBJ_DESTROY, oJArr 
 
END 

After saving and compiling the above files (array2d.java in Java and ArrayDemo.pro in IDL), update the jbexamples.jar file in the resource/bridges/import/java directory with the new compiled class and run the ArrayDemo routine in IDL. The routine should produce the following results:

array2d short(2, 3) = 23 (should be 23) 
SHORTARRIDL   INT = Array[3, 4] 
shortArrIDL[2, 3] = 23 (should be 23) 
array2d short(2, 3) = 999 (should be 999) 
array2d short(0, 0) = 0 (should be 0) 
array2d short(1, 0) = 1 (should be 1) 
array2d short(2, 0) = 2 (should be 2) 
array2d short(0, 1) = 10 (should be 10) 
array2d long(0, 1) = 10 (should be 10) 

Accessing URLs Example

This example finds and reads a given URL, which is contained in a file named URLReader.java. IDL then accesses this data through the URLRead routine, which is in a file named urlread.pro.

Example Code
These files are located in the resource/bridges/import/java/examples directory of the IDL distribution. Run this example procedure by entering urlread at the IDL command prompt or view the file in an IDL Editor window by entering .EDIT urlread.pro.

The URLReader.java file contains the following text for reading a given URL in Java:

import java.io.*; 
import java.net.*; 
 
public class URLReader 
{ 
   private ByteArrayOutputStream m_buffer; 
 
  // ******************************************************** 
  // 
  // Constructor.  Create the reader 
  // 
  // ******************************************************** 
   public URLReader() { 
      m_buffer = new ByteArrayOutputStream(); 
   } 
          
  // ******************************************************** 
  // 
  // readURL: read the data from the URL into our buffer 
  // 
  //    returns: number of bytes read (0 if invalid URL) 
  // 
  // NOTE: reading a new URL clears out the previous data 
  // 
  // ******************************************************** 
   public int readURL(String sURL) { 
      URL url; 
      InputStream in = null; 
 
m_buffer.reset();  // reset our holding buffer to 0 bytes 
 
      int total_bytes = 0; 
      byte[] tempBuffer = new byte[4096]; 
      try { 
         url = new URL(sURL); 
         in = url.openStream(); 
 
         int bytes_read; 
         while ((bytes_read = in.read(tempBuffer)) != -1) { 
            m_buffer.write(tempBuffer, 0, bytes_read); 
            total_bytes += bytes_read; 
         } 
      } catch (Exception e) { 
         System.err.println("Error reading URL: "+sURL); 
         total_bytes = 0; 
      } finally { 
         try {  
            in.close();  
            m_buffer.close();  
         } catch (Exception e) {} 
      } 
 
      return total_bytes; 
   } 
 
  // ******************************************************** 
  // 
  // getData: return the array of bytes 
  // 
  // ******************************************************** 
   public byte[] getData() { 
     return m_buffer.toByteArray(); 
   } 
 
  // ******************************************************** 
  // 
  // main: reads URL and reports # of byts reads 
  // 
  //   Usage: java URLReader <URL> 
  // 
  // ******************************************************** 
 
  public static void main(String[] args) {   
     if (args.length != 1) 
        System.err.println("Usage: URLReader <URL>"); 
     else { 
        URLReader o = new URLReader(); 
        int b = o.readURL(args[0]); 
        System.out.println("bytes="+b); 
     } 
  } 
 
} 

The urlread.pro file contains the following text for inputting an URL as an IDL string and then accessing its data within IDL:

FUNCTION URLRead, sURLName 
 
; Create an URLReader. 
oJURLReader = OBJ_NEW('IDLjavaObject$URLReader', 'URLReader') 
 
; Read the URL data into our Java-side buffer. 
nBytes = oJURLReader->ReadURL(sURLName) 
 
;PRINT, 'Read ', nBytes, ' bytes' 
 
; Pull the data into IDL. 
byteArr = oJURLReader->GetData() 
 
; Cleanup Java object. 
OBJ_DESTROY, oJURLReader 
 
; Return the data. 
RETURN, byteArr 
 
END 

After saving and compiling the above files (URLReader.java in Java and urlread.pro in IDL), you can run the URLRead routine in IDL. This routine is a function with one input argument, which should be a IDL string containing an URL. For example:

address = 'http://www.ittvis.com' 
data = URLRead(address) 

Accessing Grayscale Images Example

This example creates a a grayscale ramp image within a Java class, which is contained in a file named GreyBandsImage.java. IDL then accesses this data through the ShowGreyImage routine, which is in the showgreyimage.pro file.

Example Code
These files are located in the resource/bridges/import/java/examples directory of the IDL distribution. Run this example procedure by entering showgreyimage at the IDL command prompt or view the file in an IDL Editor window by entering.EDIT showgreyimage.pro.

The GreyBandsImage.java file contains the following text for creating a grayscale image in Java:

import java.awt.*; 
import java.awt.image.*; 
 
public class GreyBandsImage extends BufferedImage 
{ 
 // Members 
 private int m_height; 
 private int m_width; 
 
 
 // 
 // ctor 
 // 
 public GreyBandsImage() { 
    super(100, 100, BufferedImage.TYPE_INT_ARGB); 
    generateImage(); 
    m_height = 100; 
    m_width = 100; 
 } 
 
 // 
 // private method to generate the image 
 // 
 private void generateImage() { 
    Color c; 
    int width  = getWidth(); 
    int height = getHeight(); 
    WritableRaster raster = getRaster(); 
    ColorModel model = getColorModel(); 
 
    int BAND_PIXEL_WIDTH = 5; 
    int nBands = width/BAND_PIXEL_WIDTH; 
    int greyDelta = 255 / nBands; 
    for (int i=0 ; i < nBands; i++) { 
          c = new Color(i*greyDelta, i*greyDelta, i*greyDelta); 
          int argb = c.getRGB(); 
          Object colorData = model.getDataElements(argb, null); 
 
          for (int j=0; j < height; j++)  
             for (int k=0; k < BAND_PIXEL_WIDTH; k++)  
                raster.setDataElements(j, (i*5)+k, colorData); 
           
    } 
 } 
 
 // 
 // mutators 
 // 
 public int[] getRawData() { 
   Raster oRaster = getRaster(); 
   Rectangle oBounds = oRaster.getBounds();  
   int[] data = new int[m_height * m_width * 4]; 
 
   data = oRaster.getPixels(0,0,100,100, data); 
   return data; 
 } 
 public int getH() {return m_height; } 
 public int getW() {return m_width; } 
 
} 

The showgreyimage.pro file contains the following text for accessing the grayscale image within IDL:

PRO ShowGreyImage 
 
; Construct the GreyBandImage in Java. This is a sub-class of 
; BufferedImage. It is actually a 4 band image that happens to 
display bands in greyscale. It is 100x100 pixels. 
oGrey = OBJ_NEW('IDLjavaObject$GreyBandsImage', 'GreyBandsImage') 
 
; Get the 4 byte pixel values. 
data = oGrey -> GetRawData() 
 
; Get the height and width. 
h = oGrey -> GetH() 
w = oGrey -> GetW() 
 
; Display the graphic in an IDL window 
WINDOW, 0, XSIZE = 100, YSIZE = 100 
TV, REBIN(data, h, w) 
 
; Cleanup 
OBJ_DESTROY, oGrey 
 
END 

After saving and compiling the above files (GreyBandsImage.java in Java and showgreyimage.pro in IDL), you can run the ShowGreyImage routine in IDL. The routine should produce the following image:

Figure 5-1: Java Grayscale Image Example

IDLJavaGrayscale.gif

Accessing RGB Images Example

This example imports an RGB (red, green, and blue) image from the IDL distribution into a Java class. The image is in the glowing_gas.jpg file, which is in the examples/data directory of the IDL distribution. The Java class also displays the image in a Java Swing user-interface. Then, the image is accessed into IDL and displayed with the new iImage tool.

Example Code
The Java and IDL code for this example is provided in the resource/bridges/import/java/examples directory, but the Java code has not been built as part of the jbexamples.jar file.

Note
This example uses functionality only available in Java 1.4 and later.

Note
Due to a Java bug, this example (and any other example using Swing on AWT) will not work on Linux platforms.

The first and main Java class is FrameTest, which creates the Java Swing application that imports the image from the glowing_gas.jpg file. Copy and paste the following text into a file, then save it as FrameTest.java:

import java.awt.*; 
import java.awt.image.*; 
import java.awt.event.*; 
import javax.swing.*; 
import javax.swing.event.*; 
import java.io.File; 
 
public class FrameTest extends JFrame { 
 
 RSIImageArea c_imgArea; 
 int m_xsize; 
 int m_ysize; 
 Box c_controlBox; 
     
 public FrameTest() { 
 
  super("This is a JAVA Swing Program called from IDL"); 
  // Dispose the frame when the sys close is hit 
  setDefaultCloseOperation(DISPOSE_ON_CLOSE); 
  m_xsize = 350; 
  m_ysize = 371; 
  buildGUI(); 
 
 } 
 
 public void buildGUI() { 
 
  c_controlBox = Box.createVerticalBox(); 
 
  JLabel l1 = new JLabel("Example Java/IDL Interaction"); 
  JButton bLoadFile = new JButton("Load new file"); 
  bLoadFile.addActionListener(new ActionListener() { 
   public void actionPerformed(ActionEvent e) { 
    JFileChooser chooser = new JFileChooser(new 
     File("c:\\ITT\\IDL63\\EXAMPLES\\DATA")); 
    chooser.setDialogTitle("Enter a JPEG file"); 
    if (chooser.showOpenDialog(FrameTest.this) == 
     JFileChooser.APPROVE_OPTION) { 
 
      java.io.File fname = chooser.getSelectedFile(); 
      String filename = fname.getPath(); 
      System.out.println(filename); 
      c_imgArea.setImageFile(filename); 
    } 
   } 
  }); 
 
  JButton b1 = new JButton("Close this example"); 
  b1.addActionListener(new ActionListener() { 
   public void actionPerformed(ActionEvent e) { 
    dispose(); 
   } 
  }); 
 
  c_imgArea = new 
   RSIImageArea("c:\\itt\\idl63\\examples\\data\\glowing_gas.jpg", 
    new Dimension(m_xsize,m_ysize)); 
 
  Box mainBox = Box.createVerticalBox(); 
  Box rowBox = Box.createHorizontalBox();        
  rowBox.add(b1); 
  rowBox.add(bLoadFile); 
 
  c_controlBox.add(l1); 
  c_controlBox.add(rowBox); 
  mainBox.add(c_controlBox); 
  mainBox.add(c_imgArea); 
 
  getContentPane().add(mainBox); 
 
  pack(); 
  setVisible(true); 
  c_imgArea.displayImage(); 
  c_imgArea.addResizeListener(new RSIImageAreaResizeListener() { 
   public void areaResized(int newx, int newy) { 
    Dimension cdim = c_controlBox.getSize(null); 
    Insets i = getInsets(); 
    newx = i.left + i.right + newx; 
    newy = i.top + cdim.height + newy + i.bottom; 
    setSize(new Dimension(newx, newy)); 
   } 
  }); 
 } 
 
 public void setImageData(int [] imgData, int xsize, int ysize) { 
  MemoryImageSource ims = new MemoryImageSource(xsize, ysize,  
   imgData, 0, ysize); 
  Image imgtmp = createImage(ims); 
  Graphics g = c_imgArea.getGraphics(); 
  g.drawImage(imgtmp, 0, 0, null); 
 
 } 
 
 public void setImageData(byte [][][] imgData, int xsize,  
  int ysize) { 
 
  System.out.println("SIZE = "+xsize+"x"+ysize); 
  int newArray [] = new int[xsize*ysize]; 
  int pixi = 0; 
  int curpix = 0; 
  short [] currgb = new short[3]; 
  for (int i=0;i<m_xsize;i++) { 
   for (int j=0;j<m_ysize;j++) { 
    for (int k=0;k<3;k++) { 
     currgb[k] = (short) imgData[k][i][j]; 
     currgb[k] = (currgb[k] < 128) ? (short) currgb[k] : (short) 
      (currgb[k]-256); 
    } 
    curpix = (int) currgb[0] *  + 
     ((int) currgb[1] * (int) Math.pow(2,8)) + 
      ((int) currgb[2] * (int) Math.pow(2,16)); 
    if (pixi % 1000 == 0) 
     System.out.println("PIXI = "+pixi+" "+curpix); 
    newArray[pixi++] = curpix; 
   } 
  } 
 
  MemoryImageSource ims = new MemoryImageSource(xsize, ysize,  
   newArray, 0, ysize); 
  c_imgArea.setImageObj(c_imgArea.createImage(ims)); 
 
 } 
 
 public byte[][][] getImageData()  
 { 
  int width = 1; 
  int height = 1; 
  PixelGrabber pGrab; 
 
  width = m_xsize; 
  height = m_ysize; 
                  
  // pixarray for the grab - 3D bytearray for display 
  int [] pixarray = new int[width*height]; 
  byte [][][] bytearray = new byte[3][width][height]; 
 
 
  // create a pixel grabber 
  pGrab = new PixelGrabber(c_imgArea.getImageObj(),0,0,  
  width,height, pixarray, 0, width); 
 
  // grab the pixels from the image 
  try { 
   boolean b = pGrab.grabPixels(); 
  } catch (InterruptedException e) { 
   System.err.println("pixel grab interrupted"); 
   return bytearray; 
  } 
 
  // break down the 32-bit integers from the grab into 8-bit bytes 
  // and fill the return 3D array 
  int pixi = 0; 
  int curpix = 0; 
  for (int j=0;j<m_ysize;j++) { 
   for (int i=0;i<m_xsize;i++) { 
    curpix = pixarray[pixi++]; 
    bytearray[0][i][j] = (byte) ((curpix >> 16) & 0xff); 
    bytearray[1][i][j] = (byte) ((curpix >>  8) & 0xff); 
    bytearray[2][i][j]  = (byte) ((curpix      ) & 0xff); 
   } 
  } 
  return bytearray; 
 } 
 
 
 public static void main(String [] args) { 
  FrameTest f = new FrameTest(); 
 } 
 
} 
 

Note
The above text is for the FrameTest class that accesses the glowing_gas.jpg file in the examples/data directory of a default installation of IDL on a Windows system. The file's location is specified as c:\\ITT\\IDL70\\EXAMPLES\\DATA in the above text. If the glowing_gas.jpg file is not in the same location on system, edit the text to change the location of this file to match your system.

The FrameTest class uses two other user-defined classes, RSIImageArea and RSIImageAreaResizeListener. These classes help to define the viewing area and display the image in Java. Copy and paste the following text into a file, then save it as RSIImageArea.java:

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.util.Vector; 
import java.io.File; 
 
public class RSIImageArea extends JComponent implements 
 MouseMotionListener, MouseListener { 
 
 
 Image c_img; 
 int m_boxw = 100; 
 int m_boxh = 100; 
 Dimension c_dim; 
 boolean m_pressed = false; 
 int m_button = 0; 
 Vector c_resizelisteners = null; 
 
 public RSIImageArea(String imgFile, Dimension dim) { 
 
  c_img = getToolkit().getImage(imgFile); 
  c_dim = dim; 
  setPreferredSize(dim); 
  setSize(dim); 
  addMouseMotionListener(this); 
  addMouseListener(this); 
 
 } 
 
 public void addResizeListener(RSIImageAreaResizeListener l) { 
  if (c_resizelisteners == null) c_resizelisteners = new Vector(); 
  if (! c_resizelisteners.contains(l))  c_resizelisteners.add(l); 
 }  
 public void removeResizeListener(RSIImageAreaResizeListener l) { 
  if (c_resizelisteners == null) return; 
  if (c_resizelisteners.contains(l)) c_resizelisteners.remove(l); 
 } 
 
 public void displayImage() { 
  repaint(); 
 } 
 
 public void paint(Graphics g) { 
 
  int xsize = c_img.getWidth(null); 
  int ysize = c_img.getHeight(null); 
  if (xsize != -1 && ysize != -1) { 
   if (xsize != c_dim.width || ysize != c_dim.height) { 
    c_dim.width = xsize; 
    c_dim.height = ysize; 
    setPreferredSize(c_dim); 
    setSize(c_dim); 
    if (c_resizelisteners != null) { 
     RSIImageAreaResizeListener l = null; 
     for (int j=0;j<c_resizelisteners.size();j++) { 
      l = (RSIImageAreaResizeListener) 
       c_resizelisteners.elementAt(j); 
      l.areaResized(xsize, ysize); 
     } 
    } 
   } 
  } 
  g.drawImage(c_img, 0, 0, null); 
 } 
 
 public void setImageFile(String fileName) {	   
  c_img = null; 
  c_img = getToolkit().getImage(fileName); 
  repaint();	 
 } 
 
 
 public Image getImageObj() { 
  return c_img; 
 } 
 
 public void setImageObj(Image img) { 
  c_img = img; 
  repaint(); 
 } 
 
 public void drawZoomBox(MouseEvent e) { 
  int bx = e.getX() - m_boxw/2;	     
  bx = (bx >=0) ? bx :0; 
  int by = e.getY() - m_boxh/2; 
  by = (by >=0) ? by :0; 
  int ex = bx + m_boxw; 
  if (ex > c_dim.width) { 
   ex = c_dim.width; 
   bx = c_dim.width-m_boxw; 
  } 
  int ey = by + m_boxh; 
  if (ey > c_dim.height) { 
   ey = c_dim.height; 
   by = c_dim.height-m_boxh; 
  } 
 
  repaint(); 
  Graphics g = getGraphics(); 
  g.drawImage(c_img, bx, by, ex, ey, bx+(m_boxw/4), by+(m_boxh/4), 
   ex-(m_boxw/4),ey-(m_boxh/4), null); 
  g.setColor(Color.white); 
  g.drawRect(bx, by, m_boxw, m_boxh); 
 
 } 
 
 public void mouseDragged(MouseEvent e) { 
  drawZoomBox(e); 
 } 
 
 public void mouseMoved(MouseEvent e) { 
 
  Graphics g = getGraphics(); 
  if (m_pressed && (m_button == 1)) { 
   drawZoomBox(e);		 
   g.setColor(Color.white); 
   g.drawString("DRAG", 10,10); 
  } else { 
 
   g.setColor(Color.white); 
   String s = "("+e.getX()+","+e.getY()+")"; 
   repaint(); 
   g.drawString(s, e.getX(), e.getY()); 
  } 
 
 } 
 
 public void mouseClicked(MouseEvent e) {} 
 public void mouseEntered(MouseEvent e) {} 
 public void mouseExited(MouseEvent e) {} 
 
 public void mousePressed(MouseEvent e) { 
  m_pressed = true; 
  m_button = e.getButton(); 
  repaint(); 
  if (m_button == 1) drawZoomBox(e); 
 } 
 
 public void mouseReleased(MouseEvent e) { 
  m_pressed = false; 
  m_button = 0; 
 }        	 
} 

And copy and paste the following text into a file, then save it as RSIImageAreaResizeListener.java:

public interface RSIImageAreaResizeListener { 
 public void areaResized(int newx, int newy); 
} 

Compile these classes in Java. Then either update the jbexamples.jar file in the resource/bridges/import/java directory with the new compiled class, place the resulting compiled classes in your Java class path, or edit the JVM Classpath setting in the IDL-Java bridge configuration file to specify the location (path) of these compiled classes. See Location of the Bridge Configuration File for more information.

With the Java classes compiled, you can now access them in IDL. Copy and paste the following text into the IDL Editor window, then save it as ImageFromJava.pro:

PRO ImageFromJava 
; Create a Swing Java object and have it load image data 
; into IDL. 
 
; Create the Java object first. 
oJSwing = OBJ_NEW('IDLjavaObject$FrameTest', 'FrameTest') 
 
; Get the image from the Java object. 
image = oJSwing -> GetImageData() 
PRINT, 'Loaded Image Information:' 
HELP, image 
 
; Delete the Java object. 
OBJ_DESTROY, oJSwing 
 
; Interactively display the image. 
IIMAGE, image 
 
END 

After compiling the above routine, you can run it in IDL. This routine produces the following Java Swing application.

Figure 5-2: Java Swing Application Example

IDLJavaSwing.gif

Then, the routine produces the following iImage tool.

Figure 5-3: iImage Tool from Java Swing Example

IDLJavaIIMAGE.gif

Note
After IDL starts the Java Swing application, the two displays are independent of each other. If a new image is loaded into the Java application, the IDL iImage tool is not updated. If the iImage tool modifies the existing image or opens a new image, the Java Swing application is not updated.