Skip to Content
go-dicom(3)

Reading and writing files

How go-dicom reads a DICOM file, what you get back, how to query and change its attributes, and how to write it again, in Go and on the command line. It is for anyone who handles files with the library, and above all for code that reads files it did not make.

Overview

filereader parses a file into a DICOMFile: the file meta group, the data elements as the file holds them, and what the read noticed (warnings, truncation). GetDataset builds a Dataset from it, with text decoded into UTF-8; that is the type you query and change. filewriter writes a data set back as a Part 10 file in the transfer syntax you name.

A data set holds data elements keyed by tag. A sequence element holds items, and each item is a data set of its own:

Values are not converted to Go types when read. A data element's value is bytes: text decoded into UTF-8, binary numbers little endian whatever the transfer syntax. You read it through a getter that knows its VR.

Read a file

f, err := os.Open("ct.dcm")
if err != nil {
	return err
}
defer f.Close()

df, err := filereader.ReadDICOMFile(filebase.NewFileReader(f))
if err != nil {
	return err
}
fmt.Println(df.FileMetaInfo.TransferSyntaxUID, df.ExplicitVR, df.IsLittleEndian)
ds := df.GetDataset()

DICOMFile holds more than the elements:

FieldWhat it says
FileMetaInfoThe group 0002 attributes, typed: SOP Class and Instance UIDs, transfer syntax, implementation
MetaElementsThe group 0002 elements as they were in the file
DataElementsThe data set's elements as read, nested items in Items
HasPreambleWhether the file began with the 128-byte preamble and DICM. False means a raw data set with no meta group
DeflatedThe data set was inflated before it was read
WarningsNon-fatal findings, in words: unknown or retired tags, VR mismatches, elements out of order
TagOrderViolationsElements whose tag is not greater than the one before them (PS3.5 7.1), up to a thousand
Truncated, OverrunThe file ended inside an element, or a length ran past its item or sequence
StoppedA Visit function ended the read early

Each element in DataElements has a Position (the offsets of its tag, length and value in the file), which is what go-dicom show --json prints.

A file without the preamble is read as a raw data set, its encoding judged from its first element, with a warning. A file that is not DICOM at all is then often read as a short, truncated raw data set rather than refused, so check HasPreamble when you expect a Part 10 file.

Read untrusted files with limits

ReadDICOMFile reads every value into memory and bounds nothing but the size of the file. For a file from somewhere else, set limits with ReadDICOMFileWithOptions:

func readUntrusted(path string) (*filereader.DICOMFile, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	df, err := filereader.ReadDICOMFileWithOptions(filebase.NewFileReader(f), filereader.ReadOptions{
		SkipBulkData:   true,     // leave Pixel Data and large binary values in the file
		MaxValueLength: 16 << 20, // refuse a value over 16 MiB before allocating it
		MaxHeaderBytes: 64 << 20, // refuse a parsed header over about 64 MiB
		Logger:         slog.New(slog.DiscardHandler),
	})
	if err != nil {
		var tooLong *filereader.ValueTooLongError
		if errors.As(err, &tooLong) {
			return nil, fmt.Errorf("%s: %s holds %d bytes", path, tooLong.Tag, tooLong.Length)
		}
		// The kind's String is a fixed phrase, with nothing from the file in it.
		return nil, fmt.Errorf("%s: %s", path, filereader.ErrorKind(err))
	}
	if !df.HasPreamble {
		return nil, fmt.Errorf("%s: not a DICOM Part 10 file", path)
	}
	return df, nil
}

Run on CT_small.dcm, the truncated MR_truncated.dcm and a text file, with the element count, Truncated, the Pixel Data element and the warnings printed:

ct.dcm 258 elements, truncated: false
  Pixel Data left in the file: true 32768 bytes at 6300
MR_truncated.dcm 71 elements, truncated: true
  warning: file is truncated at position 1500; the incomplete element was dropped and the 71 elements before it are intact: invalid length for tag (7FE0,0010): value runs past the end of the stream: declared length 8192 exceeds 8130 bytes remaining
notdicom.txt: not a DICOM Part 10 file

The options:

OptionDefaultWhat it does
SkipBulkDataoffLeaves Pixel Data, its fragments, and binary values (OB, OD, OF, OL, OV, OW, UN) longer than BulkDataThreshold in the file. The element keeps its Length and Position and has ValueSkipped set
BulkDataThreshold0The longest binary value still read under SkipBulkData. Pixel Data is skipped at any length
MaxValueLengthno limitA longer value ends the read with a *ValueTooLongError, before it is allocated
MaxHeaderBytesno limitBounds the whole parsed tree, counted per element, item and value held; passing it ends the read with a *HeaderTooLargeError
Visitnot setShown each element as it is read; decides whether it is kept (below)
Loggerconfig.LoggerWhere this read, and the data set built from it, log

Some limits are always on: sequences nest at most filereader.MaxSequenceDepth (64) deep, a deflated data set may inflate to at most filereader.MaxInflatedDatasetSize (256 MiB), and no element may declare more bytes than the stream holds. The full table is in CONFORMANCE.md §7.

Warning

With no limits set, a crafted file can make a read allocate as much as the file is long, and a header of millions of small items fills memory however long each value is. Set MaxValueLength and MaxHeaderBytes for any file you did not make.

A data set built from a file read with SkipBulkData has the skipped values empty. To rewrite such a file without holding its pixels, see Rewrite a file without loading its pixels.

Read element by element

ReadOptions.Visit is shown each element once it is whole, at any depth, and returns VisitKeep or VisitDiscard. What it discards is not kept and gives back what it cost MaxHeaderBytes, so memory follows what you keep, however large the header. Returning ErrStopVisit ends the read there without an error, and DICOMFile.Stopped says so.

This keeps the Patient module and the Study Instance UID, nothing inside a sequence, and stops reading once past the Study Instance UID:

studyUID := tag.New(0x0020, 0x000D)
df, err := filereader.ReadDICOMFileWithOptions(filebase.NewFileReader(f), filereader.ReadOptions{
	Visit: func(v filereader.Visit) (filereader.VisitAction, error) {
		if len(v.Path) > 0 {
			return filereader.VisitDiscard, nil // nothing inside sequences
		}
		if v.Element.Tag > studyUID {
			return filereader.VisitDiscard, filereader.ErrStopVisit // past what is wanted
		}
		if v.Element.Tag.Group() == 0x0010 || v.Element.Tag == studyUID {
			return filereader.VisitKeep, nil
		}
		return filereader.VisitDiscard, nil
	},
})
if err != nil {
	return err
}
fmt.Println("stopped early:", df.Stopped)
for _, e := range df.DataElements {
	fmt.Printf("%s %s %q\n", e.Tag, e.VR, e.Value)
}

On CT_small.dcm:

stopped early: true
(0010,0010) PN "CompressedSamples^CT1 "
(0010,0020) LO "1CT1"
(0010,0030) DA ""
(0010,0040) CS "O "
(0010,1002) SQ ""
(0010,1010) AS "000Y"
(0010,1030) DS "0.000000"
(0010,21B0) LT ""
(0020,000D) UI "1.3.6.1.4.1.5962.1.2.1.20040119072730.12322\x00"

A sequence is shown after its items, holding the ones that were kept. Values are as stored: padding is still there, and text is not decoded. filereader.TextEncodings and filereader.DecodeText decode it with the Specific Character Set. File meta elements are not shown to Visit.

Truncated and damaged files

A read goes on past what it can recover from and reports it:

  • Truncated. An element declaring more bytes than the file holds is dropped, the elements before it kept, Truncated set and a warning naming the offset. pydicom instead returns the element with the bytes that were there; go-dicom does not, because a short pixel buffer renders as an image with nothing looking wrong (CONFORMANCE.md §8.4).
  • Overrun. An element runs past the end of its item, or an item past its sequence. Reading goes on, as pydicom's does, and Overrun is set: what followed may have been read from the wrong place.
  • Out of order. Tags that repeat or go backwards are kept, listed in TagOrderViolations and counted in TagOrderViolationCount.

Each is also among Warnings. A program that acts on them reads the fields, not the text of a warning.

When a read fails outright, the error carries a kind. filereader.ErrorKind(err) gives it, and errors.Is matches its sentinel:

KindSentinelMeaning
ReadErrorTruncatedErrTruncatedThe file ends before what it declares, where the read cannot go on
ReadErrorBadPreambleErrBadPreambleThe file does not begin as Part 10 does
ReadErrorBadFileMetaErrBadFileMetaThe file meta group cannot be read
ReadErrorMalformedElementErrMalformedElementAn element, item or sequence whose bytes do not mean what the encoding says
ReadErrorNestingTooDeepErrNestingTooDeepSequences nested past MaxSequenceDepth
ReadErrorBadDeflateErrBadDeflateA deflated data set that does not inflate, or expands too far
ReadErrorValueTooLongErrValueTooLongRefused by MaxValueLength; *ValueTooLongError has the tag, length and offset
ReadErrorHeaderTooLargeErrHeaderTooLargeRefused by MaxHeaderBytes; *HeaderTooLargeError has where

Note

The error's own message can quote what the file held. The kind's String() is a fixed phrase ("the file is truncated"), safe to log or show for a file you do not trust.

Query a data set

By keyword or by tag

fmt.Println(ds.GetStringByKeyword("Modality"))           // "CT"; "" when absent
fmt.Println(ds.ContainsByKeyword("PatientBirthDate"))    // true
elem, ok := ds.Get(tag.New(0x0028, 0x0010))              // the element itself
elem, ok = ds.GetByKeyword("Rows")                       // the same

GetStringByKeyword trims padding and returns text. GetTextValue(tag) gives the decoded text of a tag, and GetPersonName(tag) a person name with its parts:

pn, err := ds.GetPersonName(tag.New(0x0010, 0x0010))
if err != nil {
	return err
}
fmt.Println(pn.FamilyName(), pn.GivenName()) // CompressedSamples CT1

GetTextValue refuses a PN element and asks for GetPersonName.

Several values

Values in a text element are separated by a backslash, and GetStringByKeyword returns them joined. The values package splits numbers held as text (DS, IS):

spacing := values.MultiStringFloat(ds.GetStringByKeyword("PixelSpacing")) // [0.661468 0.661468]
types := strings.Split(ds.GetStringByKeyword("ImageType"), `\`)           // [ORIGINAL PRIMARY AXIAL]

Binary numbers

US, SS, UL, SL, FL, FD and the other binary VRs are held as bytes, little endian in a data set whatever the file's transfer syntax. Read them with encoding/binary, or with values.ConvertValue, which gives the first value:

rows, ok := ds.GetByKeyword("Rows")
if ok {
	b, _ := rows.Bytes()
	fmt.Println(rows.VR, binary.LittleEndian.Uint16(b)) // US 128
}

The image attributes (Rows, Columns, Bits Allocated, Pixel Representation, Rescale Slope and Intercept and the rest) are gathered in one call by ds.GetPixelDataInfo().

Sequences

seq, err := ds.GetSequence(ds.KeywordToTag("OtherPatientIDsSequence"))
if err != nil {
	return err // also when the sequence is not there
}
for i := 0; i < seq.Length(); i++ {
	element, _ := seq.Get(i)
	item := element.(*dataset.Dataset)
	fmt.Println(item.GetStringByKeyword("PatientID"), item.GetStringByKeyword("TypeOfPatientID"))
}

ds.ForEach visits the top-level elements; it does not descend into sequences. ds.IterAll does, giving each element with the data set it is in.

Private attributes

A private element is found through its creator, as PS3.5 7.8.1 has it, not by a fixed tag. GetAllPrivateCreators lists the creators by group, and GetPrivateValue(group, offset, creator) reads an element of a block:

v, err := ds.GetPrivateValue(0x0009, 0x02, "GEMS_IDEN_01") // (0009,1002) in this file
if err != nil {
	return err
}
fmt.Printf("%q\n", v) // "CT01"

PrivateBlock(group, creator) gets the block, reserving one when the creator has none, and adds to it:

pb, err := ds.PrivateBlock(0x0029, "ACME 1.0")
if err != nil {
	return err
}
if err := pb.AddNew(0x10, dataelem.LO, "v2"); err != nil {
	return err
}
fmt.Println(pb.GetTag(0x10)) // (0029,1110): block 0x10 already belongs to another creator

Set, add and remove

// Change an attribute that is there.
if err := ds.SetStringByKeyword("PatientName", "Roe^Richard"); err != nil {
	return err
}
// Add one, or replace it, with its VR. Numbers and lists are Go values.
if err := ds.AddByKeyword("ImageComments", dataelem.LT, "re-read"); err != nil {
	return err
}
if err := ds.Add(dataelem.NewDataElement(tag.New(0x0028, 0x0030), dataelem.DS, []float64{0.5, 0.5})); err != nil {
	return err
}
ds.RemoveByKeyword("PatientBirthDate")

Add and AddByKeyword replace an element already there. The value is rendered for its VR when written (dataelem.ValueBytes): any Go integer or float, or a slice of them, for US, SS, UL, SL, UV, SV, FL, FD, IS and DS; []string for any text VR; tag.Tag for AT; []byte or a string as they are. A value that does not fit its VR is an error, not a different number: 70000 is refused for a US.

Warning

SetStringByKeyword and SetValue are for an attribute that is already there. On an absent one they create an element with VR OB, which an explicit VR file then stores as OB. Add a new attribute with AddByKeyword or Add and its VR.

To build a sequence, append data sets as items:

item := dataset.NewDataset()
if err := item.AddByKeyword("CodeValue", dataelem.SH, "T-D1100"); err != nil {
	return err
}
if err := ds.AppendToSequence(tag.New(0x0008, 0x2218), item); err != nil { // Anatomic Region Sequence
	return err
}

AppendToSequence creates the sequence when it is not there.

Tags and the dictionary

tag.Tag is a uint32, group in the upper half:

t := tag.New(0x0010, 0x0010)
t, err := tag.ParseTag("(0010,0010)") // also "0x00100010" and "00100010"
fmt.Println(t, t.GetKeyword(), t.GetName(), t.GetVR()) // (0010,0010) PatientName Patient's Name PN
fmt.Println(tag.GlobalDictionary().GetByKeyword("StudyInstanceUID")) // (0020,000D)

ParseTag does not take 0010,0020 without the parentheses; the command line does. t.IsPrivate(), t.IsPrivateCreator() and t.IsRetired() classify a tag. The private dictionary (tag.FindPrivateTagVendor, tag.GetPrivateTagsByVendor) is GDCM's, and supplies the VR of a private element read from an implicit VR file when it is written (CONFORMANCE.md §8.3).

Write a file

filewriter writes a preamble, the meta group and the data set:

out, err := os.Create("new.dcm")
if err != nil {
	return err
}
w := filewriter.NewDICOMFileWriter(filebase.NewFileWriter(out))
w.SetFileMetaInfo(&filewriter.FileMetaInfo{
	MediaStorageSOPClassUID:    ds.GetStringByKeyword("SOPClassUID"),
	MediaStorageSOPInstanceUID: ds.GetStringByKeyword("SOPInstanceUID"),
	TransferSyntaxUID:          filewriter.StorageTransferSyntax(ds),
})
if err := w.AddDataElements(filewriter.ElementsFromDataset(ds)); err != nil {
	return err
}
if err := w.Write(); err != nil {
	return err
}
if err := out.Close(); err != nil {
	return err
}
  • The transfer syntax in FileMetaInfo decides how the data set is encoded: explicit or implicit VR, byte order, deflated. The meta group itself is always Explicit VR Little Endian (PS3.10 7.1).
  • StorageTransferSyntax(ds) gives Explicit VR Little Endian for native pixel data and the data set's own syntax for compressed pixel data, whose syntax is the only record of which codec made the fragments. To change the pixel encoding, transcode first (Pixel data).
  • The Implementation Class UID and version name are this library's unless you set them.
  • ElementsFromDataset descends into sequences and writes each element with the VR the data set resolves (OB or OW for Pixel Data becomes OB at 8 bits allocated or fewer, OW above).

A data set can be made from nothing: dataset.NewDataset(), then AddByKeyword for each attribute, with uid.Generate() for a new UID (a 2.25. UUID UID) and uid.CTImageStorage().String() or another SOP Class.

Rewrite a file without loading its pixels

Read with SkipBulkData, build the data set with GetDatasetWithValuesIn, and give the writer the file as its value source. Pixel Data is copied from the input as it is written:

in, err := os.Open("ct.dcm")
if err != nil {
	return err
}
defer in.Close()

df, err := filereader.ReadDICOMFileWithOptions(filebase.NewFileReader(in),
	filereader.ReadOptions{SkipBulkData: true})
if err != nil {
	return err
}
ds, source, err := df.GetDatasetWithValuesIn(in)
if err != nil {
	return err
}
if err := ds.AddByKeyword("SeriesDescription", dataelem.LO, "Rewritten"); err != nil {
	return err
}

out, err := os.Create("ct-rewritten.dcm")
if err != nil {
	return err
}
w := filewriter.NewDICOMFileWriter(filebase.NewFileWriter(out))
w.SetFileMetaInfo(&filewriter.FileMetaInfo{
	MediaStorageSOPClassUID:    df.FileMetaInfo.MediaStorageSOPClassUID,
	MediaStorageSOPInstanceUID: df.FileMetaInfo.MediaStorageSOPInstanceUID,
	TransferSyntaxUID:          df.FileMetaInfo.TransferSyntaxUID,
})
w.SetValueSource(source, df.IsLittleEndian)
if err := w.AddDataElements(filewriter.ElementsFromDataset(ds)); err != nil {
	return err
}
if err := w.Write(); err != nil {
	return err
}
if err := out.Close(); err != nil {
	return err
}

This works for a deflated file too: source then inflates the original stream as the values are asked for, a window at a time.

Deflated files

Deflated Explicit VR Little Endian (1.2.840.10008.1.2.1.99) compresses the whole data set after the meta group. The reader inflates it, up to 256 MiB, and sets DICOMFile.Deflated; the positions of the elements then count bytes of the inflated data set, not of the file. DICOMFile.ValueSource(file) gives a reader over those inflated bytes. The writer deflates when the meta group names this syntax (filewriter.DeflatedExplicitVRLittleEndianUID), element by element, without holding the body in memory.

This is not the same as Deflated Image Frame Compression (1.2.840.10008.1.2.8.1), which compresses only the pixel data; see Pixel data.

DICOM JSON and XML

The DICOM JSON Model (PS3.18 Annex F) and the Native DICOM Model (PS3.19 Annex A) are read and written by the data set:

doc, err := ds.ToDICOMJSONWithOptions(dataset.DICOMJSONOptions{
	BulkDataThreshold: 1024, // values of 1024 bytes or more become a BulkDataURI
	BulkDataURIFunc:   func(t tag.Tag) string { return "bulk/" + t.Hex() },
})
if err != nil {
	return err
}
text, err := json.Marshal(doc)
if err != nil {
	return err
}

back := dataset.NewDataset()
if err := back.FromDICOMJSONString(string(text)); err != nil {
	return err
}

xml, err := ds.ToDICOMXML()
if err != nil {
	return err
}
fromXML := dataset.NewDataset()
if err := fromXML.FromDICOMXML(xml); err != nil {
	return err
}

ToDICOMJSONString() gives the document as text with every value inline. ToDICOMXMLWithOptions and FromDICOMXMLWithOptions handle BulkData references in XML. JSON writes DS and IS as JSON numbers, so 5.000000 comes back as 5; XML keeps them as written. A data set's ToJSON and ToJSONString are a different, flat format for reading, without sequences or binary values.

Read without the codecs

filereader/attributes is the same parser without GetDataset, frames or waveforms, so a program that only indexes headers does not link the pixel codecs. It returns the same element types, and attributes.DICOMJSON writes the same JSON ToDICOMJSON does, with a hook that decides per value:

file, err := attributes.Read(filebase.NewFileReader(f), attributes.ReadOptions{SkipBulkData: true})
if err != nil {
	return err
}
encodings := attributes.TextEncodings(file.DataElements, nil)
for _, e := range file.DataElements {
	if e.Tag.Group() == 0x0010 {
		fmt.Println(e.Tag, e.VR, attributes.DecodeText(e.VR, e.Value, encodings))
	}
}

doc, err := attributes.DICOMJSON(file.DataElements, attributes.JSONOptions{
	BulkData: func(v attributes.BulkDataValue) attributes.BulkDataDecision {
		if v.InFile { // left in the file by SkipBulkData: point at it
			return attributes.BulkDataDecision{URI: fmt.Sprintf("bulk/%d+%d", v.Offset, v.Length)}
		}
		return attributes.BulkDataDecision{} // inline
	},
})

For CT_small.dcm, Pixel Data comes out as {"BulkDataURI":"bulk/6300+32768","vr":"OW"}. A value left in the file for which the hook gives neither a URI nor Omit is an error.

On the command line

CommandWhat it does
show fileEvery element as stored; --top, --exclude-private, --full, --json (schema)
show file::ElementOne element, whole, by keyword, tag or name
info fileA summary; --stats, --verbose
diff a bElement by element, into sequences; exit status 0 equal, 1 different, 2 could not compare
modifySet, insert or delete attributes, at any depth, private ones by creator
convert --format dicom-json / dicom-xmlThe DICOM JSON or Native DICOM Model of a file
createA file from DICOM JSON, DICOM XML, a PNG or JPEG, or a PDF
codify fileThe Go program that builds the data set
$ go-dicom modify -set PatientName='Roe^Richard' -insert AccessionNumber=A1234 -delete PatientBirthDate ct.dcm ct-mod.dcm
Wrote ct-mod.dcm: 3 change(s), transfer syntax 1.2.840.10008.1.2.1
$ go-dicom diff ct.dcm ct-mod.dcm --ignore-meta --ignore SpecificCharacterSet
--- ct.dcm
+++ ct-mod.dcm
(0008,0050) Accession Number
- SH
+ SH A1234
(0010,0010) Patient's Name
- PN CompressedSamples^CT1
+ PN Roe^Richard
(0010,0030) Patient's Birth Date
- DA
$ go-dicom modify -insert 'ReferencedStudySequence[0].ReferencedSOPInstanceUID=1.2.3' ct.dcm ct-mod2.dcm
Wrote ct-mod2.dcm: 1 change(s), transfer syntax 1.2.840.10008.1.2.1
$ go-dicom modify -set Rows=70000 ct.dcm x.dcm
Error: modify: -set Rows=70000: (0028,0010) US: "70000" is not an unsigned 16-bit integer

modify checks every value against its VR before writing anything, keeps the transfer syntax and copies pixel data untouched. -new-uid gives the instance a new SOP Instance UID; without it the UID is kept. go-dicom modify -h has the path syntax, private attributes included.

Round trip through JSON and XML:

$ go-dicom convert ct.dcm ct.json --format dicom-json
Wrote ct.json: DICOM JSON, 258 top-level elements
$ go-dicom create ct.json ct-copy.dcm
Wrote ct-copy.dcm: from DICOM JSON, 1.2.840.10008.1.2.1
$ go-dicom convert ct.dcm ct.xml --format dicom-xml
Wrote ct.xml: Native DICOM Model XML, 258 top-level elements
$ go-dicom create ct.xml ct-copy2.dcm
Wrote ct-copy2.dcm: from the Native DICOM Model, 1.2.840.10008.1.2.1
$ go-dicom diff ct.dcm ct-copy2.dcm --ignore-meta
--- ct.dcm
+++ ct-copy2.dcm
(0008,0005) Specific Character Set
- CS ISO_IR 100
+ CS ISO_IR 192

create from JSON takes binary values from InlineBinary, or from a BulkDataURI naming a file inside -bulk-dir; an http: URI is refused, not fetched. The JSON carries no transfer syntax, so -syntax names it when the pixel data is compressed. convert --format json (the default) is a flat rendering for reading and cannot be read back.

Limits and gotchas

  • Values are bytes. GetStringByKeyword on a binary number returns its raw bytes as a string. Use the binary readers.
  • GetDataset builds a new data set on every call. Keep the one you change: a second call starts again from what was read, and DICOMFile.DataElements does not see your changes.
  • SetStringByKeyword does not add. See the warning under Set, add and remove.
  • Text comes back as UTF-8, and is written as UTF-8. A file read and written again declares ISO_IR 192; see Character sets.
  • No limits by default. Set MaxValueLength and MaxHeaderBytes for untrusted input.
  • A truncated element is dropped, not shortened (CONFORMANCE.md §8.4).
  • GetDataset logs. Building a data set validates it and logs what it finds, retired tags for instance, to config.Logger or the read's Logger; see Configuration and errors.
  • A JSON round trip rewrites DS and IS as the shortest number; XML does not.

See also

On this page