user3136641 user3136641 - 1 year ago 163
Java Question

How to convert JPG image to DICOM file using dcm4che-3.2.1?

I can set the attributes and create the dicom file, but I can not write the image to the dicom file?

Answer Source

I've tried it with an image I have and it works but I expect it won't work for RGB images. Something like this though

    BufferedImage jpg = File("myjpg.jpg"));

    //Convert the image to a byte array 
    DataBufferUShort buff = (DataBufferUShort) jpg.getData().getDataBuffer();
    short[] data = buff.getData();
    ByteBuffer byteBuf = ByteBuffer.allocate(2*data.length);
    int i = 0;
    while (data.length > i) {

    //Copy a header 
    DicomInputStream dis = new DicomInputStream(new File("fileToCopyheaderFrom.dcm"));
    Attributes meta = dis.readFileMetaInformation();
    Attributes attribs = dis.readDataset(-1, Tag.PixelData);

    //Change the rows and columns
    attribs.setInt(Tag.Rows, VR.US, jpg.getHeight());
    attribs.setInt(Tag.Columns, VR.US, jpg.getWidth());
    //Attributes attribs = new Attributes();

    //Write the file
    attribs.setBytes(Tag.PixelData, VR.OW, byteBuf.array());
    DicomOutputStream dcmo = new DicomOutputStream(new File("myDicom.dcm"));

Edit 1

I've assumed your image has an Unsigned short Data Buffer here.

DataBufferUShort buff = (DataBufferUShort) jpg.getData().getDataBuffer();

To handle other data buffers you should check the type , cast acordingly and then convert to a byte array. For a byte Buffer it should be easy

DataBufferByte buff = (DataBufferByte) jpg.getData().getDataBuffer();



where numOfBank is 0 for you image

should return a byte array