Click here to Skip to main content
Click here to Skip to main content

Converting a DICOM Image to a Common Graphic Format and Vice Versa with DCMTK and CxImage

, 10 Nov 2005 CPOL
Rate this:
Please Sign up or sign in to vote.
Converting a DICOM file to BMP/JPG and vice versa


This article presents a minimum runnable toy application as a starting point to show how to convert a DICOM image to common graphic formats (i.e. BMP, JPG, TIF, etc.) and vice versa. Our sample application is based on two open source libraries, they are DCMTK and CxImage.


The DICOM standard (Digital Imaging and Communications in Medicine) is a standard created by the National Electrical Manufacturers Association (NEMA) to ease the distribution and exchange of medical images, such as CT scans, MRIs and ultrasound. In this article, we will focus on file format conversions. The file format is described in Part 10 of the DICOM standard, which you can download from here[^]. There is also a brief introduction to the file format available here.

DCMTK is a widely used open source implementation of the DICOM standard; it is a collection of C/C++ libraries and applications with complete source code. To compile the sample in this article, you need to download DCMTK first. If you have trouble building the downloaded DCMTK package, please refer to DCMTK for Dummies.

Another library used in this article is CxImage, it is a C++ class that can load, save, display and transform images in a very simple and fast way. It supports almost all the common graphic types, such as BMP, JPG, TIF, PNG, etc. In this article, we will expand this library to support displaying and transforming DICOM images by using the DICOM format encoding/decoding features provided by DCMTK. Download CxImage and follow its usage guidance to make sure it can be compiled successfully on your machine.

Using the Code

We simply derive our CxImageDCM class from the base class CxImage. Doing so enables CxImageDCM class to load and decode common graphics using the methods inherited from the base class. There are three extra methods in the derived class, LoadDCM(…), SaveAsDCM(…), SaveAsJPG(…), they are used to decode, encode and convert a DICOM image, respectively.

class CxImageDCM : public CxImage  
    virtual ~CxImageDCM();
    bool LoadDCM(const TCHAR* filename);
    bool SaveAsDCM(const TCHAR* filename);
    bool SaveAsJPG(const TCHAR* fileName);


Load DCM

In the sample application, a DICOM image is loaded and decoded with the classes provided by DCMTK, then it is converted to a temporary bitmap file for later manipulations:

bool CxImageDCM::LoadDCM(const TCHAR* filename)
    DcmFileFormat *dfile = new DcmFileFormat();
    OFCondition cond = dfile->loadFile(filename, EXS_Unknown,
    if (cond.bad()) {
    E_TransferSyntax xfer = 
    DicomImage *di = new DicomImage(dfile, xfer, 
                         CIF_AcrNemaCompatibility, 0, 1);
    if (di->getStatus() != EIS_Normal)
    return CxImage::Load("c:\\from_dicom.bmp",CXIMAGE_FORMAT_BMP);

Converting from DCM

After loading a DCM file, you can save it as a common graphic file using the encoding features provided by CxImage, or you may also use DCMTK’s encoding plugins to do the conversion (however, CxImage supports more formats):

bool CxImageDCM::SaveAsJPG(const TCHAR* fileName)
{//you may also use DCMTK's JPG encoding plug-in
    return CxImage::Save(fileName,CXIMAGE_FORMAT_JPG);


Converting to DCM

To convert a common graphic file to a DCM file, you need to load the common graphic first, then set the necessary tag and copy the pixel data to the destination DCM file:

bool CxImageDCM::SaveAsDCM(const TCHAR* filename)
    char uid[100]; 
    DcmFileFormat fileformat; 
    DcmDataset *dataset = fileformat.getDataset(); 
    /* ... */
    /* ... */    
    //add more tags here
    /* ... */ 
    BYTE* pData=new BYTE[GetHeight()*info.dwEffWidth];
    BYTE* pSrc=GetBits(head.biHeight-1);
    BYTE* pDst=pData;
    for(long y=0; y < head.biHeight; y++){
                 pData, GetHeight()*info.dwEffWidth); 
    delete[] pData;
    OFCondition status = fileformat.saveFile(filename, 
    if (status.bad()) 
        AfxMessageBox("Error: cannot write DICOM file ");
    return true;     

Points of Interest

In this article, the encoding feature provided by CxImage is used to convert a DICOM image to a JPG file (or other formats that CxImage supports). Actually, DCMTK already has a full-fledged utility called dcmj2pnm to convert a DICOM image to a BMP, PNG, TIF or JPG image. For other formats, that dcmj2pnm doesn’t support, such as GIF, TGA, PCX, WBMP, etc., you may use CxImage’s encoding features to write your own converting functions. One thing that I need to clarify here is that our sample application is only a toy utility to give you a starting point. To write a decent DICOM image converter, you need to consider many more DICOM related options. For more information, you can refer to the implementation of dcmj2pnm. (It is included in the DCMTK source code package.)

From my experience, CxImage is easy to use; it "can load, save, display and transform images in a simple and fast way". However, I find it annoying when you have to derive a new image encoder/decoder from the base class, CxImage. The base class must know all the derived classes to give a polymorphic behavior. Fortunately, in our sample, the derived class CxImageDCM needs only the encoding/decoding functions it inherits from the base class, so I didn’t bother to touch the source code of CxImage.



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer
China China
idling/looking for a new job...

Comments and Discussions

QuestionIs it possible a simple console application? Pinmemberazman_356-Nov-06 23:39 
Generalhelp convert DICOM file to bmp, png... Pinmemberloitls19-Oct-06 6:38 
GeneralRe: help convert DICOM file to bmp, png... PinstaffChristian Graus19-Oct-06 6:57 
GeneralRe: help convert DICOM file to bmp, png... Pinmemberloitls19-Oct-06 10:30 
Thanks for your reply!Smile | :)
Espero que entiendas español, ya es mas facil para mi explicarte lo que quiero hacer:
Quiero convertir imagenes de archivos DICOM a formatos mas conocidos, esactamante BMP, PPM,PNG,TIFF y JPEG y viceversa.
Estoy usando las librerias DICOM toolkit (dcmtk, Microsoft Visual c++ 6.0, Windows XP.
con esta instruccion puedo guardar una imagen del archivo DICOM en formato BMP
puedo guardar una imagen en formato PPM con la siguiente instruccion:
pero tambien necesito gardar imgenes en los formatos antes mencionados (PNG,TIFF y JPEG)
en DCMTK existe una herramienta llamada dcm2pnm, puedes verlo en:[^]
sucede que ya trate de usarla de la siguente manera:
Formato a seguir explicado en la documentacion:
dcm2pnm [options] dcmfile-in [pnmfile-out]
casos prscticos

C:\dcmtk\bin>dcm2pnm.exe +oj test.dcm test.jpg;
C:\dcmtk\bin>dcm2pnm es la ruta del ejecutable cm2pnm.exe
+oj y/o +obt es la opcion de conversion a formato JPEG y BMP
test.dcm es el nombre del archivo DICOM
test.jpg y/o test.bmp es el archivo de salida en formato JPEG, BMP
asi que si

pero no consigo resultado alguno.
Asi que si alguen me puede explicar que es lo que estoy haciendo mal o como debo usar la herramienta, se lo agradecere mucho


QuestionConersion to Dicom PinmemberHarpreet Kaur18-Sep-06 1:08 
AnswerRe: Conersion to Dicom Pinmemberlxwde18-Sep-06 3:09 
GeneralRe: Conersion to Dicom PinmemberHarpreet Kaur18-Sep-06 18:57 
GeneralRe: Conersion to Dicom PinstaffChristian Graus19-Oct-06 7:10 
GeneralI hardly see my dicom files PinmemberDabe4-Sep-06 8:47 
GeneralRe: I hardly see my dicom files PinstaffChristian Graus19-Oct-06 7:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150327.1 | Last Updated 10 Nov 2005
Article Copyright 2005 by lxwde
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid