Пример #1
0
def write_sequence_item(fp: DicomIO, dataset: Dataset,
                        encodings: List[str]) -> None:
    """Write a `dataset` in a sequence to the file-like `fp`.

    This is similar to writing a data_element, but with a specific tag for
    Sequence Item.

    See DICOM Standard, Part 5, :dcm:`Section 7.5<sect_7.5.html>`.

    Parameters
    ----------
    fp : file-like
        The file-like to write the encoded data to.
    dataset : Dataset
        The :class:`Dataset<pydicom.dataset.Dataset>` to write to `fp`.
    encodings : list of str
        The character encodings to use on text values.
    """
    fp.write_tag(ItemTag)  # marker for start of Sequence Item
    length_location = fp.tell()  # save location for later.
    # will fill in real value later if not undefined length
    fp.write_UL(0xffffffff)
    write_dataset(fp, dataset, parent_encoding=encodings)
    if getattr(dataset, "is_undefined_length_sequence_item", False):
        fp.write_tag(ItemDelimiterTag)
        fp.write_UL(0)  # 4-bytes 'length' field for delimiter item
    else:  # we will be nice and set the lengths for the reader of this file
        location = fp.tell()
        fp.seek(length_location)
        fp.write_UL(location - length_location - 4)  # 4 is length of UL
        fp.seek(location)  # ready for next data_element
Пример #2
0
def write_dataset(
        fp: DicomIO,
        dataset: Dataset,
        parent_encoding: Union[str, List[str]] = default_encoding) -> int:
    """Write a Dataset dictionary to the file. Return the total length written.
    """
    _harmonize_properties(dataset, fp)

    if None in (dataset.is_little_endian, dataset.is_implicit_VR):
        name = dataset.__class__.__name__
        raise AttributeError(
            f"'{name}.is_little_endian' and '{name}.is_implicit_VR' must "
            f"be set appropriately before saving")

    if not dataset.is_original_encoding:
        dataset = correct_ambiguous_vr(dataset, fp.is_little_endian)

    dataset_encoding = cast(
        Union[None, str, List[str]],
        dataset.get('SpecificCharacterSet', parent_encoding))

    fpStart = fp.tell()
    # data_elements must be written in tag order
    tags = sorted(dataset.keys())

    for tag in tags:
        # do not write retired Group Length (see PS3.5, 7.2)
        if tag.element == 0 and tag.group > 6:
            continue

        with tag_in_exception(tag):
            write_data_element(fp, dataset.get_item(tag), dataset_encoding)

    return fp.tell() - fpStart