In this tutorial, we are going to learn how to convert the Dicom file into Png or Jpg.
If we want to present the Dicom image in the browser or sometimes it might be required to convert it to the desired png or jpg image to manipulate process and analysis.
For this, we can use a very useful library called SimpleItk. Please go over the installation process from this tutorial. If we are dealing with medical images like Dicom, the library is very useful for image processing, manipulation, and analysis. So we suggest using the library.
For reading Dicom metadata please follow this tutorial.
Now, let's begin with the conversion of the Dicom file, for this let's create a sample Java class called DicomConverter.java and create a method for reading the Dicom file
import org.itk.simple.*;
public static ImageFileReader getDcmImageFileReader(String imagePath) {
ImageFileReader imageFileReader = new ImageFileReader();
imageFileReader.setImageIO("GDCMImageIO");
imageFileReader.setFileName(imagePath);
return imageFileReader;
}
Now, let's add the method for converting the Dicom
public static void convert(ImageFileReader imageFileReader, String outputPath) {
Image image = imageFileReader.execute();
SimpleITK.writeImage(image, outputPath);
}
Create the main method to run the conversion
public static void main(String[] args) {
String inputDicomPath = "inputdicom_path/N2D_0001.dcm";
String outputPath = "output_path/test.png";
try {
ImageFileReader imageFileReader = getDcmImageFileReader(inputDicomPath);
convert(imageFileReader, outputPath);
} catch (Exception e) {
e.printStackTrace();
}
}
For Jpg use the .jpg output path.
The overall implementation looks like below:
package dicom;
import org.itk.simple.*;
public class DicomConverter {
public static void main(String[] args) {
String inputDicomPath = "/N2D_0001.dcm";
String outputPath = "/test.png";
try {
ImageFileReader imageFileReader = getDcmImageFileReader(inputDicomPath);
convert(imageFileReader, outputPath);
} catch (Exception e) {
e.printStackTrace();
}
}
public static ImageFileReader getDcmImageFileReader(String imagePath) {
ImageFileReader imageFileReader = new ImageFileReader();
imageFileReader.setImageIO("GDCMImageIO");
imageFileReader.setFileName(imagePath);
return imageFileReader;
}
public static void convert(ImageFileReader imageFileReader, String outputPath) {
Image image = imageFileReader.execute();
SimpleITK.writeImage(image, outputPath);
}
}