Search code examples
javaimagej

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [B


I tried to read an image from loci tools and save it to FileSaver from imagej but, I got this error when running it

ImagePlus[] imps = BF.openImagePlus("path/to/my/file");
for (ImagePlus imp : imps)new FileSaver(imp).saveAsRaw("E:/test.raw");

when I run the code, it shows

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [B
at ij.io.ImageWriter.write(ImageWriter.java:272)
at ij.io.FileSaver.saveAsRaw(FileSaver.java:494)
at Skripsi.dcmtoraw.main(dcmtoraw.java:16)

Solution

  • This is a bug, although it's not trivial to say whether the bug is in ImageJ 1.x, or in the Bio-Formats plugins.

    In the ImageJ 1.x code, the ImageWriter assumes (unchecked) that the pixels array is an Object[] when the image is a stack, and a byte[] when it's a single image plane. However, it seems that Bio-Formats produces ImagePlus objects whose pixels are Object[] even for single planes. (Is your image a single plane?)

    You could probably work around the issue by using the Bio-Formats Exporter plugin to save your data.

    Or you could use the ImageJ2 API, which will use SCIFIO under the hood:

    /**
     * Adapted from the
     * <a href="https://github.com/imagej/imagej-tutorials">ImageJ Tutorials</a>
     * {@code LoadAndDisplayDataset} tutorial.
     */
    @Plugin(type = Command.class, menuPath = "Plugins>My Useful Command")
    public class UsefulCommand implements Command {
    
      @Parameter
      private DatasetIOService datasetIOService;
    
      @Parameter
      private LogService log;
    
      @Parameter
      private File destination;
    
      @Parameter
      private Dataset image;
    
      @Override
      public void run() {
        try {
          image = datasetIOService.save(image, destination.getAbsolutePath());
        }
        catch (final IOException exc) {
          log.error(exc);
        }
      }
    
    }