javadicomdcm4che

how to add metadata to an image (with java code) and then convert it to dicom


I found a java code that converts a jpg and a Dicom(it takes the metadata fri¡om that one) files to a final Dicom one. What I want to do is convert the jpg image into a Dicom one, generating the metadata with java code.

BufferedImage jpg = ImageIO.read(new File("myjpg.jpg"));

// Convert the image to a byte array    
DataBuffer buff = jpg.getData().getDataBuffer();
DataBufferUShort buffer = new DataBufferUShort(buff.getSize());

for (int i = 0; i < buffer.getSize(); ++i)
    buffer.setElem(i, buff.getElem(i));

short[] data = buffer.getData();
ByteBuffer byteBuf = ByteBuffer.allocate(2 * data.length);
int i = 0;
while (data.length > i) {
    byteBuf.putShort(data[i]);
    i++;
}
// Copy a header
DicomInputStream dis = new DicomInputStream(new File("fileToCopyheaderFrom.dcm"));
Attributes meta = dis.readFileMetaInformation();
Attributes attribs = dis.readDataset(-1, Tag.PixelData);
dis.close();
// Change the rows and columns
attribs.setInt(Tag.Rows, VR.US, jpg.getHeight());
attribs.setInt(Tag.Columns, VR.US, jpg.getWidth());
System.out.println(byteBuf.array().length);
// Write the file
attribs.setBytes(Tag.PixelData, VR.OW, byteBuf.array());
DicomOutputStream dcmo = new DicomOutputStream(new File("myDicom.dcm"));
dcmo.writeFileMetaInformation(meta);
attribs.writeTo(dcmo);
dcmo.close();

Solution

  • I am not expert in toolkit (and of-course Java as well).

    Your "// Copy a header" section reads the source DICOM file and holds all the attributes in Attributes attribs variable.

    Then, your "// Change the rows and columns" section modifies few attributes as per need.

    Then, your "// Write the file" section simply add the attributes read from source file to destination file.

    Now, you want to bypass the source DICOM file and convert plain JPEG to DICOM with adding attributes yourself.

    Replace your "// Copy a header" section to build the instance of Attributes.

    Attributes attribs = new Attributes();
    attribs.setString(Tag.StudyDate, VR.DA, "20110404");
    attribs.setString(Tag.StudyTime, VR.TM, "15");
    

    The tags mentioned in above example are for example only. You have to decide yourself which tags you want to include. Note that specifications have defined Types 1, 1C, 2, 2C and 3 for tags depending on the SOP class you are dealing with.
    While adding the tags, you have to take care of correct VR as well. Specifications talk about that thing as well.
    I cannot explain all this here; too broad.