How to read the content of a DICOM file in Java?

Yayatcm picture Yayatcm · Jul 11, 2015 · Viewed 10.8k times · Source

A DICOM file contains a series of CAT scan images. Is there an implementation of a DICOM library in Java that can read the files and extract the images stored in them? I would like to store those images into a BufferedImage data type.

Answer

malaguna picture malaguna · Sep 18, 2015

You can use dcm4che-3.3.X. This new rewrite of the fabulous framework comes with jai-imageio library fully integrated and you don't need to download and configure it anymore.

Reading meta-information of a Dicom file is a mater of creating a org.dcm4che3.io.DicomInputStream from dicom file and parsing the stream with a class that implements org.dcm4che3.io.DicomInputHandler interface. You have to implements this methods:

void readValue(DicomInputStream dis, Attributes attrs) throws IOException;
void readValue(DicomInputStream dis, Sequence seq) throws IOException;
void readValue(DicomInputStream dis, Fragments frags) throws IOException;
void startDataset(DicomInputStream dis) throws IOException;
void endDataset(DicomInputStream dis) throws IOException;

startDataset and endDataset methods are launched when the stream is open/closed. The read methods are invoked when attributes, sequence or fragments are found. You can see a complete sample implementation in dcm4che/dcm4che-tool/dcm4che-tool-dcmdump.

To read dicom image into a java.awt.image.BufferedImage you need to get an javax.imageio.stream.ImageInputStream from a dicom file this way javax.imageio.ImageIO.createImageInputStream(dicomFile) where dicomFile is a java.io.File.

If you are wondering how this simple code works, this is because of dcm4che-imageio plugin.

Once again you can see a complete example implementation in dcm4che/dcm4che-tool/dcm4che-tool-dcm2jpg.

Obviously, you need a properly configured maven pom.xml with all dependencies you need, at least:

<dependencies>
  <dependency>
    <groupId>org.dcm4che</groupId>
    <artifactId>dcm4che-imageio</artifactId>
    <version>3.3.7</version>
  </dependency>
  <dependency>
    <groupId>org.dcm4che</groupId>
    <artifactId>dcm4che-imageio-rle</artifactId>
    <version>3.3.7</version>
    <scope>runtime</scope>
  </dependency>
  <dependency>
    <groupId>com.sun.media</groupId>
    <artifactId>jai_imageio</artifactId>
    <version>1.2-pre-dr-b04</version>
    <scope>runtime</scope>
  </dependency>
  <dependency>
    <groupId>org.dcm4che.tool</groupId>
    <artifactId>dcm4che-tool-common</artifactId>
    <version>3.3.7</version>
    <scope>compile</scope>
  </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
  </dependency>
</dependencies>

and also dcm4che maven repo

<repositories>
  <repository>
    <id>www.dcm4che.org</id>
    <name>dcm4che Repository</name>
    <url>http://www.dcm4che.org/maven2</url>
</repository>

Hope it helps.