Using DicomInputHandler

DicomInputStream uses an implementation of the interface DicomInputHandler to handle the reading of data values from the stream. By default, DicomInputStream uses itself as the DicomInputHandler but the user can provide an alternate implementation. Some implementations are included with dcm4che2, including the StopTagInputHandler which is shown in the following example:

// don't read the pixel data element or any later elements
dicomInputStream.setHandler(new StopTagInputHandler(Tag.PixelData))

The following example shows an input handler that handles the pixel data element specially:

import java.io.*;
import org.dcm4che2.data.*;
import org.dcm4che2.io.*;

/**
 * Input handler that provides special handling for pixel data element
 */
public class PixelDataInputHandler implements DicomInputHandler {
    public boolean readValue(final DicomInputStream din) throws IOException {
	if (din.tag() == Tag.PixelData && din.level() == 0) {
	    // handle data however you like; for example, load into buffer
	    byte[] buf = new byte[din.valueLength()];
	    din.readFully(buf);
	    // return true to indicate the parsing should continue
	    return true;
	} else {
	    // allow the DicomInputStream to handle the data normally
	    return din.readValue(din);
	}
    }
}