Java Image Buffer

This example demonstrate efficient access to the Image’s buffer in SimpleITK with Java. The SimpleITK Image class has the java.nio.Buffer Image::getBufferAsBuffer(void) method. The ` class has derived types for Java’s signed integers, float, and double types. These derived buffer type are returned, when the SimpleITK Image’s pixel type as scalar, vector, or complex corresponds. Additionally, the UInt16 types are returned as a CharBuffer, other wise a ByteBuffer is returned. The returned buffer is the Image’s buffer and no copy has occurred. However, SimpleITK’s copy on write policies are followed, and Image::MakeUnique is called.



 import org.itk.simple.Image;
 import org.itk.simple.SimpleITK;
 import org.itk.simple.PixelIDValueEnum;

 class ImageGetSetBuffer {

    public static void main(String args[]) {

      if (args.length < 1) {
        System.out.format("Usage: ImageSetGetBuffer <input>");

      Image image = SimpleITK.readImage(args[0]);

      // The loaded image may be of any type and number of components, so convert to float,
      // so there is a known type.
      if (image.getNumberOfComponentsPerPixel() != 1) {
        image = SimpleITK.cast(image, PixelIDValueEnum.sitkVectorFloat32);
      } else {
        image = SimpleITK.cast(image, PixelIDValueEnum.sitkFloat32);

      java.nio.FloatBuffer buffer = (java.nio.FloatBuffer)image.getBufferAsBuffer();


      for (int i = 0; i < 10 && buffer.hasRemaining(); ++i) {

      while (buffer.hasRemaining()) {