예제 #1
0
파일: XDicom.cs 프로젝트: xiaotie/mdcm
        private static void LoadSequence(XElement parent, IList <DcmItem> items, XDicomOptions options)
        {
            foreach (DcmItem item in items)
            {
                if (!Flags.IsSet(options, XDicomOptions.IncludePixelData) && item.Tag == DicomTags.PixelData)
                {
                    continue;
                }

                XElement attr = new XElement("attr");

                attr.SetAttributeValue("tag", item.Tag.Card.ToString("x8"));
                attr.SetAttributeValue("vr", item.VR.VR);

                if (item is DcmItemSequence)
                {
                    DcmItemSequence seq = (DcmItemSequence)item;
                    attr.SetAttributeValue("len", -1);

                    foreach (DcmItemSequenceItem si in seq.SequenceItems)
                    {
                        XElement itm = new XElement("item");
                        LoadSequence(itm, si.Dataset.Elements, options);
                        attr.Add(itm);
                    }
                }
                else if (item is DcmFragmentSequence)
                {
                    DcmFragmentSequence seq = (DcmFragmentSequence)item;
                    attr.SetAttributeValue("len", -1);

                    LoadFragmentOffsetTable(attr, seq);
                    foreach (ByteBuffer fi in seq.Fragments)
                    {
                        LoadFragmentItem(attr, seq.VR, fi);
                    }
                }
                else
                {
                    DcmElement element = (DcmElement)item;
                    attr.SetAttributeValue("len", element.Length);
                    attr.Add(element.GetValueString());
                }

                if (Flags.IsSet(options, XDicomOptions.Comments))
                {
                    parent.Add(new XComment(item.Tag.Entry.Name));
                }
                parent.Add(attr);
            }
        }
예제 #2
0
파일: XDicom.cs 프로젝트: xiaotie/mdcm
        private static void Save(XElement parent, DcmDataset dataset)
        {
            foreach (XElement attr in parent.Elements("attr"))
            {
                DicomTag tag = DicomTag.Parse(attr.Attribute("tag").Value);
                DicomVR  vr  = DicomVR.Lookup(attr.Attribute("vr").Value);
                int      len = int.Parse(attr.Attribute("len").Value, CultureInfo.InvariantCulture);

                if (vr == DicomVR.SQ)
                {
                    DcmItemSequence seq = new DcmItemSequence(tag);
                    foreach (XElement itm in attr.Elements("item"))
                    {
                        DcmItemSequenceItem item = new DcmItemSequenceItem();
                        Save(itm, item.Dataset);
                        seq.AddSequenceItem(item);
                    }
                    dataset.AddItem(seq);
                }
                else if (len == -1)
                {
                    DcmFragmentSequence seq = new DcmFragmentSequence(tag, vr);
                    bool first = true;
                    foreach (XElement itm in attr.Elements("item"))
                    {
                        if (first)
                        {
                            SaveFragmentOffsetTable(itm, seq);
                            first = false;
                        }
                        else
                        {
                            SaveFragmentItem(itm, seq);
                        }
                    }
                    dataset.AddItem(seq);
                }
                else
                {
                    DcmElement element = DcmElement.Create(tag, vr);
                    element.SetValueString(attr.FirstText());
                    dataset.AddItem(element);
                }
            }
        }
예제 #3
0
        public object this[string index]
        {
            get
            {
                if (_dataset == null)
                {
                    return(String.Empty);
                }

                DicomTag tag = null;
                if (!_map.TryGetValue(index, out tag))
                {
                    tag = DicomTag.Parse(index);
                }

                if (tag != null)
                {
                    DcmElement elem = _dataset.GetElement(tag);
                    if (elem.Length == 0)
                    {
                        return(String.Empty);
                    }
                    if (elem != null)
                    {
                        object o = elem.GetValueObject();
#if !SILVERLIGHT
                        if (_xmlEscape && o is string)
                        {
                            return(SecurityElement.Escape((string)o));
                        }
                        else
#endif
                        return(o);
                    }
                }

                return(String.Empty);
            }
        }
예제 #4
0
        public DcmPixelData(DcmDataset dataset)
        {
            _transferSyntax            = dataset.InternalTransferSyntax;
            _lossy                     = dataset.GetString(DicomTags.LossyImageCompression, "00") != "00";
            _lossyMethod               = dataset.GetString(DicomTags.LossyImageCompressionMethod, String.Empty);
            _lossyRatio                = dataset.GetString(DicomTags.LossyImageCompressionRatio, String.Empty);
            _frames                    = dataset.GetInt32(DicomTags.NumberOfFrames, 1);
            _width                     = dataset.GetUInt16(DicomTags.Columns, 0);
            _height                    = dataset.GetUInt16(DicomTags.Rows, 0);
            _bitsStored                = dataset.GetUInt16(DicomTags.BitsStored, 0);
            _bitsAllocated             = dataset.GetUInt16(DicomTags.BitsAllocated, 0);
            _highBit                   = dataset.GetUInt16(DicomTags.HighBit, (ushort)(_bitsStored - 1));
            _samplesPerPixel           = dataset.GetUInt16(DicomTags.SamplesPerPixel, 0);
            _pixelRepresentation       = dataset.GetUInt16(DicomTags.PixelRepresentation, 0);
            _planarConfiguration       = dataset.GetUInt16(DicomTags.PlanarConfiguration, 0);
            _photometricInterpretation = dataset.GetString(DicomTags.PhotometricInterpretation, String.Empty);
            _rescaleSlope              = dataset.GetDouble(DicomTags.RescaleSlope, 1.0);
            _rescaleIntercept          = dataset.GetDouble(DicomTags.RescaleIntercept, 0.0);
            _pixelDataItem             = dataset.GetItem(DicomTags.PixelData);

            _hasPixelPadding = dataset.Contains(DicomTags.PixelPaddingValue);
            if (_hasPixelPadding)
            {
                DcmElement elem = dataset.GetElement(DicomTags.PixelPaddingValue);
                if (elem is DcmUnsignedShort && elem.GetVM() > 0)
                {
                    _pixelPaddingValue = (elem as DcmUnsignedShort).GetValue();
                }
                else if (elem is DcmSignedShort && elem.GetVM() > 0)
                {
                    _pixelPaddingValue = (elem as DcmSignedShort).GetValue();
                }
                else
                {
                    _pixelPaddingValue = MinimumDataValue;
                }
            }
        }
예제 #5
0
        private void Load(DcmDataset ds)
        {
            _rows    = ds.GetUInt16(OverlayTag(DicomTags.OverlayRows), 0);
            _columns = ds.GetUInt16(OverlayTag(DicomTags.OverlayColumns), 0);
            _type    = ds.GetString(OverlayTag(DicomTags.OverlayType), "Unknown");

            DicomTag tag = OverlayTag(DicomTags.OverlayOrigin);

            if (ds.Contains(tag))
            {
                short[] xy = ds.GetSS(tag).GetValues();
                if (xy != null && xy.Length == 2)
                {
                    _originX = xy[0];
                    _originY = xy[1];
                }
            }

            _bitsAllocated = ds.GetUInt16(OverlayTag(DicomTags.OverlayBitsAllocated), 1);
            _bitPosition   = ds.GetUInt16(OverlayTag(DicomTags.OverlayBitPosition), 0);

            tag = OverlayTag(DicomTags.OverlayData);
            if (ds.Contains(tag))
            {
                DcmElement elem = ds.GetElement(tag);
                _data = elem.ByteBuffer.ToBytes();
            }

            _description = ds.GetString(OverlayTag(DicomTags.OverlayDescription), String.Empty);
            _subtype     = ds.GetString(OverlayTag(DicomTags.OverlaySubtype), String.Empty);
            _label       = ds.GetString(OverlayTag(DicomTags.OverlayLabel), String.Empty);

            _frames      = ds.GetInt32(OverlayTag(DicomTags.NumberOfFramesInOverlay), 1);
            _frameOrigin = ds.GetUInt16(OverlayTag(DicomTags.ImageFrameOrigin), 1);

            //TODO: include ROI
        }
예제 #6
0
        /// <summary>
        /// Read dataset from stream
        /// </summary>
        /// <param name="stopAtTag">End parsing at this tag</param>
        /// <param name="options">DICOM read options</param>
        /// <returns>Status code</returns>
        public DicomReadStatus Read(DicomTag stopAtTag, DicomReadOptions options)
        {
            // Counters:
            //  _remain - bytes remaining in stream
            //  _bytes - estimates bytes to end of dataset
            //  _read - number of bytes read from stream
            try {
                _need   = 0;
                _remain = _stream.Length - _stream.Position;

                while (_remain > 0)
                {
                    DicomReadStatus status = ParseTag(stopAtTag, options);
                    if (status == DicomReadStatus.SuccessEndRead)
                    {
                        return(DicomReadStatus.Success);
                    }
                    if (status != DicomReadStatus.Success)
                    {
                        return(status);
                    }

                    status = ParseVR(options);
                    if (status != DicomReadStatus.Success)
                    {
                        return(status);
                    }

                    status = ParseLength(options);
                    if (status != DicomReadStatus.Success)
                    {
                        return(status);
                    }

                    if (_tag.IsPrivate)
                    {
                        if (_tag.Element != 0x0000 && _tag.Element <= 0x00ff)
                        {
                            // handle UN private creator id
                            if (_vr != DicomVR.LO && Flags.IsSet(options, DicomReadOptions.ForcePrivateCreatorToLO))
                            {
                                Dicom.Debug.Log.Warn("Converting Private Creator VR from '{0}' to 'LO'", _vr.VR);
                                _vr = DicomVR.LO;
                            }
                        }
                    }

                    if (_vr == DicomVR.UN && _syntax.IsExplicitVR && Flags.IsSet(options, DicomReadOptions.UseDictionaryForExplicitUN))
                    {
                        _vr = _tag.Entry.DefaultVR;
                    }

                    if (_fragment != null)
                    {
                        status = InsertFragmentItem(options);
                        if (status != DicomReadStatus.Success)
                        {
                            return(status);
                        }
                    }
                    else if (_sqs.Count > 0 &&
                             (_tag == DicomTags.Item ||
                              _tag == DicomTags.ItemDelimitationItem ||
                              _tag == DicomTags.SequenceDelimitationItem))
                    {
                        status = InsertSequenceItem(options);
                        if (status != DicomReadStatus.Success)
                        {
                            return(status);
                        }
                    }
                    else
                    {
                        if (_sqs.Count > 0)
                        {
                            DcmItemSequence sq = _sqs.Peek();
                            if (sq.StreamLength != UndefinedLength)
                            {
                                long end = sq.StreamPosition + 8 + sq.StreamLength;
                                if (_syntax.IsExplicitVR)
                                {
                                    end += 2 + 2;
                                }
                                if ((_stream.Position - _offset) >= end)
                                {
                                    if (_sds.Count == _sqs.Count)
                                    {
                                        _sds.Pop();
                                    }
                                    _sqs.Pop();
                                }
                            }
                        }

                        if (_len == UndefinedLength)
                        {
                            if (_vr == DicomVR.SQ)
                            {
                                DcmItemSequence sq = new DcmItemSequence(_tag, _pos, _len, _endian);
                                InsertDatasetItem(sq, options);
                                _sqs.Push(sq);
                            }
                            else
                            {
                                _fragment = new DcmFragmentSequence(_tag, _vr, _pos, _endian);
                                InsertDatasetItem(_fragment, options);
                            }
                        }
                        else
                        {
                            if (_vr == DicomVR.SQ)
                            {
                                DcmItemSequence sq = new DcmItemSequence(_tag, _pos, _len, _endian);
                                InsertDatasetItem(sq, options);
                                _sqs.Push(sq);
                            }
                            else
                            {
                                if (_len > _remain)
                                {
                                    return(NeedMoreData(_len));
                                }

                                DcmElement elem = DcmElement.Create(_tag, _vr, _pos, _endian, CurrentBuffer(options));
                                _remain -= _len;
                                _read   += _len;

                                InsertDatasetItem(elem, options);
                            }
                        }
                    }

                    _tag = null;
                    _vr  = null;
                    _len = UndefinedLength;
                }

                return(DicomReadStatus.Success);
            }
            catch (EndOfStreamException) {
                // should never happen
                return(DicomReadStatus.UnknownError);
            }
        }
예제 #7
0
 private object LoadDicomFieldValue(DcmElement elem, Type vtype, DicomFieldDefault deflt, bool udzl)
 {
     if (vtype.IsSubclassOf(typeof(DcmElement))) {
         if (elem != null && vtype != elem.GetType())
             throw new DicomDataException("Invalid binding type for Element VR!");
         return elem;
     } else if (vtype.IsArray) {
         if (elem != null) {
             if (vtype.GetElementType() != elem.GetValueType())
                 throw new DicomDataException("Invalid binding type for Element VR!");
             if (elem.GetValueType() == typeof(DateTime))
                 return (elem as DcmDateElementBase).GetDateTimes();
             else
                 return elem.GetValueObjectArray();
         } else {
             if (deflt == DicomFieldDefault.EmptyArray)
                 return Array.CreateInstance(vtype, 0);
             else
                 return null;
         }
     } else {
         if (elem != null) {
             if (elem.Length == 0 && udzl) {
                 return GetDefaultValue(vtype, deflt);
             }
             if (vtype != elem.GetValueType()) {
                 if (vtype == typeof(string)) {
                     return elem.GetValueString();
                 } else if (vtype == typeof(DicomUID) && elem.VR == DicomVR.UI) {
                     return (elem as DcmUniqueIdentifier).GetUID();
                 } else if (vtype == typeof(DicomTransferSyntax) && elem.VR == DicomVR.UI) {
                     return (elem as DcmUniqueIdentifier).GetTS();
                 } else if (vtype == typeof(DcmDateRange) && elem.GetType().IsSubclassOf(typeof(DcmDateElementBase))) {
                     return (elem as DcmDateElementBase).GetDateTimeRange();
                 } else if (vtype == typeof(Int32)) {
                     return Convert.ToInt32(elem.GetValueString(), 10);
                 } else if (vtype == typeof(object)) {
                     return elem.GetValueObject();
                 } else
                     throw new DicomDataException("Invalid binding type for Element VR!");
             } else {
                 return elem.GetValueObject();
             }
         } else {
             return GetDefaultValue(vtype, deflt);
         }
     }
 }
예제 #8
0
 private void InitBlock(FilterDataset enclosingInstance)
 {
     this.enclosingInstance = enclosingInstance;
     next = findNext();
 }
예제 #9
0
 public virtual System.Object next()
 {
     if (next == null)
     {
         throw new System.Exception();
     }
     DcmElement retval = next;
     next = findNext();
     return retval;
 }
예제 #10
0
 protected internal virtual DcmElement put(DcmElement el)
 {
     if (!filter(el.tag()))
     {
         throw new System.ArgumentException("" + el + " does not fit in this sub DataSet");
     }
     return backend.put(el);
 }
예제 #11
0
        /// <summary>
        /// Write dataset to stream
        /// </summary>
        /// <param name="dataset">Dataset</param>
        /// <param name="options">DICOM write options</param>
        /// <returns>Status code</returns>
        public DicomWriteStatus Write(DcmDataset dataset, DicomWriteOptions options)
        {
            TransferSyntax = dataset.InternalTransferSyntax;
            dataset.SelectByteOrder(_syntax.Endian);

            foreach (DcmItem item in dataset.Elements)
            {
                if (item.Tag.Element == 0x0000)
                {
                    continue;
                }

                if (Flags.IsSet(options, DicomWriteOptions.CalculateGroupLengths) &&
                    item.Tag.Group != _group && item.Tag.Group <= 0x7fe0)
                {
                    _group = item.Tag.Group;
                    _writer.Write((ushort)_group);
                    _writer.Write((ushort)0x0000);
                    if (_syntax.IsExplicitVR)
                    {
                        _writer.Write((byte)'U');
                        _writer.Write((byte)'L');
                        _writer.Write((ushort)4);
                    }
                    else
                    {
                        _writer.Write((uint)4);
                    }
                    _writer.Write((uint)dataset.CalculateGroupWriteLength(_group, _syntax, options));
                }

                _writer.Write((ushort)item.Tag.Group);
                _writer.Write((ushort)item.Tag.Element);

                if (_syntax.IsExplicitVR)
                {
                    _writer.Write((byte)item.VR.VR[0]);
                    _writer.Write((byte)item.VR.VR[1]);
                }

                if (item is DcmItemSequence)
                {
                    DcmItemSequence sq = item as DcmItemSequence;

                    if (_syntax.IsExplicitVR)
                    {
                        _writer.Write((ushort)0x0000);
                    }

                    if (Flags.IsSet(options, DicomWriteOptions.ExplicitLengthSequence) || (item.Tag.IsPrivate && !_syntax.IsExplicitVR))
                    {
                        int hl = _syntax.IsExplicitVR ? 12 : 8;
                        _writer.Write((uint)sq.CalculateWriteLength(_syntax, options & ~DicomWriteOptions.CalculateGroupLengths) - (uint)hl);
                    }
                    else
                    {
                        _writer.Write((uint)UndefinedLength);
                    }

                    foreach (DcmItemSequenceItem ids in sq.SequenceItems)
                    {
                        ids.Dataset.ChangeTransferSyntax(dataset.InternalTransferSyntax, null);

                        _writer.Write((ushort)DicomTags.Item.Group);
                        _writer.Write((ushort)DicomTags.Item.Element);

                        if (Flags.IsSet(options, DicomWriteOptions.ExplicitLengthSequenceItem))
                        {
                            _writer.Write((uint)ids.CalculateWriteLength(_syntax, options & ~DicomWriteOptions.CalculateGroupLengths) - (uint)8);
                        }
                        else
                        {
                            _writer.Write((uint)UndefinedLength);
                        }

                        Write(ids.Dataset, options & ~DicomWriteOptions.CalculateGroupLengths);

                        if (!Flags.IsSet(options, DicomWriteOptions.ExplicitLengthSequenceItem))
                        {
                            _writer.Write((ushort)DicomTags.ItemDelimitationItem.Group);
                            _writer.Write((ushort)DicomTags.ItemDelimitationItem.Element);
                            _writer.Write((uint)0x00000000);
                        }
                    }

                    if (!Flags.IsSet(options, DicomWriteOptions.ExplicitLengthSequence) && !(item.Tag.IsPrivate && !_syntax.IsExplicitVR))
                    {
                        _writer.Write((ushort)DicomTags.SequenceDelimitationItem.Group);
                        _writer.Write((ushort)DicomTags.SequenceDelimitationItem.Element);
                        _writer.Write((uint)0x00000000);
                    }
                }

                else if (item is DcmFragmentSequence)
                {
                    DcmFragmentSequence fs = item as DcmFragmentSequence;

                    if (_syntax.IsExplicitVR)
                    {
                        _writer.Write((ushort)0x0000);
                    }
                    _writer.Write((uint)UndefinedLength);

                    _writer.Write((ushort)DicomTags.Item.Group);
                    _writer.Write((ushort)DicomTags.Item.Element);

                    if (Flags.IsSet(options, DicomWriteOptions.WriteFragmentOffsetTable) && fs.HasOffsetTable)
                    {
                        _writer.Write((uint)fs.OffsetTableBuffer.Length);
                        fs.OffsetTableBuffer.CopyTo(_writer.BaseStream);
                    }
                    else
                    {
                        _writer.Write((uint)0x00000000);
                    }

                    foreach (ByteBuffer bb in fs.Fragments)
                    {
                        _writer.Write((ushort)DicomTags.Item.Group);
                        _writer.Write((ushort)DicomTags.Item.Element);
                        _writer.Write((uint)bb.Length);
                        bb.CopyTo(_writer.BaseStream);
                    }

                    _writer.Write((ushort)DicomTags.SequenceDelimitationItem.Group);
                    _writer.Write((ushort)DicomTags.SequenceDelimitationItem.Element);
                    _writer.Write((uint)0x00000000);
                }

                else
                {
                    DcmElement de = item as DcmElement;

                    if (_syntax.IsExplicitVR)
                    {
                        if (de.VR.Is16BitLengthField)
                        {
                            _writer.Write((ushort)de.Length);
                        }
                        else
                        {
                            _writer.Write((ushort)0x0000);
                            _writer.Write((uint)de.Length);
                        }
                    }
                    else
                    {
                        _writer.Write((uint)de.Length);
                    }

                    de.ByteBuffer.CopyTo(_writer.BaseStream);
                }
            }

            return(DicomWriteStatus.Success);
        }
예제 #12
0
        public string MakeGreyDicom(byte[] greybytes, ushort imgwidth, ushort imgheight)
        {
            DcmUID     studyUid  = DcmUID.Generate();
            DcmUID     seriesUid = DcmUID.Generate(studyUid, 1);
            DcmUID     instUid   = DcmUID.Generate(seriesUid, 1);
            DcmDataset data      = new DcmDataset(DcmTS.ExplicitVRBigEndian);      //.ImplicitVRLittleEndian  ok

            data.AddElementWithValue(DcmTags.SOPClassUID, DcmUIDs.CTImageStorage); //ComputedRadiographyImageStorage  ok
            //data.AddElementWithValue(DcmTags.SOPClassUID, DcmUIDs .SecondaryCapture);
            data.AddElementWithValue(DcmTags.StudyInstanceUID, studyUid);
            data.AddElementWithValue(DcmTags.SeriesInstanceUID, seriesUid);
            data.AddElementWithValue(DcmTags.SOPInstanceUID, instUid);//"1.3.6.1.4.1.30071.6.635719267134010719.1.1"

            //data.AddElementWithValue(DcmTags.MediaStorageSOPClassUID, DcmUIDs.ImplicitVRLittleEndian);
            //data.AddElementWithValueString(DcmTags.MediaStorageSOPClassUID, DcmUIDs.ComputedRadiographyImageStorage.ToString());

            //type 2 attributes
            ////data.AddElement(DcmTags.PrinterStatus);
            if (tags.ContainsKey("0010,0020"))
            {
                data.AddElementWithValueString(DcmTags.PatientID, tags["0010,0020"].Substring(5));
            }
            if (tags.ContainsKey("0010,0010"))
            {
                data.AddElementWithValueString(DcmTags.PatientsName, tags["0010,0010"].Substring(5));
            }
            if (tags.ContainsKey("0010,0030"))
            {
                data.AddElementWithValueString(DcmTags.PatientsBirthDate, tags["0010,0030"].Substring(5));
            }
            if (tags.ContainsKey("0010,0040"))
            {
                data.AddElementWithValueString(DcmTags.PatientsSex, tags["0010,0040"].Substring(5));
            }
            if (tags.ContainsKey("0010,1010"))
            {
                data.AddElementWithValueString(DcmTags.PatientsAge, tags["0010,1010"].Substring(5));
            }

            if (tags.ContainsKey("0008,0005"))
            {
                data.AddElementWithValueString(DcmTags.SpecificCharacterSet, tags["0008,0005"].Substring(5));
            }
            if (tags.ContainsKey("0008,0008"))
            {
                data.AddElementWithValueString(DcmTags.ImageType, tags["0008,0008"].Substring(5));
            }
            //if (tags.ContainsKey("0008,0016"))
            //    data.AddElementWithValueString(DcmTags.ContentTime, DateTime.Now.ToString());
            //if (tags.ContainsKey("0008,0018"))
            //    data.AddElementWithValueString(DcmTags.ContentTime, DateTime.Now.ToString());
            if (tags.ContainsKey("0008,0020"))
            {
                data.AddElementWithValueString(DcmTags.StudyDate, tags["0008,0020"].Substring(5));
            }
            if (tags.ContainsKey("0008,0021"))
            {
                data.AddElementWithValueString(DcmTags.SeriesDate, tags["0008,0021"].Substring(5));
            }
            if (tags.ContainsKey("0008,0022"))
            {
                data.AddElementWithValueString(DcmTags.AcquisitionDate, tags["0008,0022"].Substring(5));
            }
            if (tags.ContainsKey("0008,0023"))
            {
                data.AddElementWithValueString(DcmTags.ContentDate, tags["0008,0023"].Substring(5));
            }
            if (tags.ContainsKey("0008,002a"))
            {
                data.AddElementWithValueString(DcmTags.AcquisitionDateTime, tags["0008,002a"].Substring(5));
            }
            if (tags.ContainsKey("0008,0030"))
            {
                data.AddElementWithValueString(DcmTags.StudyTime, tags["0008,0030"].Substring(5));
            }
            if (tags.ContainsKey("0008,0031"))
            {
                data.AddElementWithValueString(DcmTags.SeriesTime, tags["0008,0031"].Substring(5));
            }
            if (tags.ContainsKey("0008,0032"))
            {
                data.AddElementWithValueString(DcmTags.AcquisitionTime, tags["0008,0032"].Substring(5));
            }
            if (tags.ContainsKey("0008,0033"))
            {
                data.AddElementWithValueString(DcmTags.ContentTime, tags["0008,0033"].Substring(5));
            }

            if (tags.ContainsKey("0008,0050"))
            {
                data.AddElementWithValueString(DcmTags.AcquisitionNumber, tags["0008,0050"].Substring(5));
            }
            if (tags.ContainsKey("0008,0060"))
            {
                data.AddElementWithValueString(DcmTags.Modality, tags["0008,0060"].Substring(5));
            }
            if (tags.ContainsKey("0008,0070"))
            {
                data.AddElementWithValueString(DcmTags.Manufacturer, tags["0008,0070"].Substring(5));
            }
            if (tags.ContainsKey("0008,0080"))
            {
                data.AddElementWithValueString(DcmTags.InstitutionName, tags["0008,0080"].Substring(5));
            }
            if (tags.ContainsKey("0008,0081"))
            {
                data.AddElementWithValueString(DcmTags.InstitutionAddress, tags["0008,0081"].Substring(5));
            }
            if (tags.ContainsKey("0008,0090"))
            {
                data.AddElementWithValueString(DcmTags.ReferringPhysiciansName, tags["0008,0090"].Substring(5));
            }
            if (tags.ContainsKey("0008,1010"))
            {
                data.AddElementWithValueString(DcmTags.StationName, tags["0008,1010"].Substring(5));
            }
            if (tags.ContainsKey("0008,1030"))
            {
                data.AddElementWithValueString(DcmTags.StudyDescription, tags["0008,1030"].Substring(5));
            }
            if (tags.ContainsKey("0008,103e"))
            {
                data.AddElementWithValueString(DcmTags.SeriesDescription, tags["0008,103e"].Substring(5));
            }
            if (tags.ContainsKey("0008,1090"))
            {
                data.AddElementWithValueString(DcmTags.ManufacturersModelName, tags["0008,1090"].Substring(5));
            }

            if (tags.ContainsKey("0018,0010"))
            {
                data.AddElementWithValueString(DcmTags.ContrastBolusAgent, tags["0018,0010"].Substring(5));
            }
            if (tags.ContainsKey("0018,0015"))
            {
                data.AddElementWithValueString(DcmTags.BodyPartExamined, tags["0018,0015"].Substring(5));
            }
            if (tags.ContainsKey("0018,0050"))
            {
                data.AddElementWithValueString(DcmTags.SliceThickness, tags["0018,0050"].Substring(5));
            }
            if (tags.ContainsKey("0018,0060"))
            {
                data.AddElementWithValueString(DcmTags.KVP, tags["0018,0060"].Substring(5));
            }
            if (tags.ContainsKey("0018,0090"))
            {
                data.AddElementWithValueString(DcmTags.DataCollectionDiameter, tags["0018,0090"].Substring(5));
            }
            if (tags.ContainsKey("0018,1000"))
            {
                data.AddElementWithValueString(DcmTags.DeviceSerialNumber, tags["0018,1000"].Substring(5));
            }
            if (tags.ContainsKey("0018,1020"))
            {
                data.AddElementWithValueString(DcmTags.SoftwareVersions, tags["0018,1020"].Substring(5));
            }
            if (tags.ContainsKey("0018,1030"))
            {
                data.AddElementWithValueString(DcmTags.ProtocolName, tags["0018,1030"].Substring(5));
            }
            if (tags.ContainsKey("0018,1041"))
            {
                data.AddElementWithValueString(DcmTags.ContrastBolusVolume, tags["0018,1041"].Substring(5));
            }
            if (tags.ContainsKey("0018,1042"))
            {
                data.AddElementWithValueString(DcmTags.ContrastBolusStartTime, tags["0018,1042"].Substring(5));
            }
            if (tags.ContainsKey("0018,1043"))
            {
                data.AddElementWithValueString(DcmTags.ContrastBolusStopTime, tags["0018,1043"].Substring(5));
            }
            if (tags.ContainsKey("0018,1044"))
            {
                data.AddElementWithValueString(DcmTags.ContrastBolusTotalDose, tags["0018,1044"].Substring(5));
            }
            if (tags.ContainsKey("0018,1046"))
            {
                data.AddElementWithValueString(DcmTags.ContrastFlowRate, tags["0018,1046"].Substring(5));
            }
            if (tags.ContainsKey("0018,1047"))
            {
                data.AddElementWithValueString(DcmTags.ContrastFlowDuration, tags["0018,1047"].Substring(5));
            }
            if (tags.ContainsKey("0018,1049"))
            {
                data.AddElementWithValueString(DcmTags.ContrastBolusIngredientConcentration, tags["0018,1049"].Substring(5));
            }
            if (tags.ContainsKey("0018,1100"))
            {
                data.AddElementWithValueString(DcmTags.ReconstructionDiameter, tags["0018,1100"].Substring(5));
            }
            if (tags.ContainsKey("0018,1110"))
            {
                data.AddElementWithValueString(DcmTags.DistanceSourceToDetector, tags["0018,1110"].Substring(5));
            }
            if (tags.ContainsKey("0018,1111"))
            {
                data.AddElementWithValueString(DcmTags.DistanceSourceToPatient, tags["0018,1111"].Substring(5));
            }
            if (tags.ContainsKey("0018,1120"))
            {
                data.AddElementWithValueString(DcmTags.GantryDetectorTilt, tags["0018,1120"].Substring(5));
            }
            if (tags.ContainsKey("0018,1130"))
            {
                data.AddElementWithValueString(DcmTags.TableHeight, tags["0018,1130"].Substring(5));
            }
            if (tags.ContainsKey("0018,1140"))
            {
                data.AddElementWithValueString(DcmTags.RotationDirection, tags["0018,1140"].Substring(5));
            }
            if (tags.ContainsKey("0018,1150"))
            {
                data.AddElementWithValueString(DcmTags.ExposureTime, tags["0018,1150"].Substring(5));
            }
            if (tags.ContainsKey("0018,1151"))
            {
                data.AddElementWithValueString(DcmTags.XRayTubeCurrent, tags["0018,1151"].Substring(5));
            }
            if (tags.ContainsKey("0018,1152"))
            {
                data.AddElementWithValueString(DcmTags.Exposure, tags["0018,1152"].Substring(5));
            }
            if (tags.ContainsKey("0018,1160"))
            {
                data.AddElementWithValueString(DcmTags.FilterType, tags["0018,1160"].Substring(5));
            }
            if (tags.ContainsKey("0018,1170"))
            {
                data.AddElementWithValueString(DcmTags.GeneratorPower, tags["0018,1170"].Substring(5));
            }
            if (tags.ContainsKey("0018,1190"))
            {
                data.AddElementWithValueString(DcmTags.FocalSpots, tags["0018,1190"].Substring(5));
            }
            if (tags.ContainsKey("0018,1200"))
            {
                data.AddElementWithValueString(DcmTags.DateOfLastCalibration, tags["0018,1200"].Substring(5));
            }
            if (tags.ContainsKey("0018,1201"))
            {
                data.AddElementWithValueString(DcmTags.TimeOfLastCalibration, tags["0018,1201"].Substring(5));
            }
            if (tags.ContainsKey("0018,1210"))
            {
                data.AddElementWithValueString(DcmTags.ConvolutionKernel, tags["0018,1210"].Substring(5));
            }
            if (tags.ContainsKey("0018,5100"))
            {
                data.AddElementWithValueString(DcmTags.PatientPosition, tags["0018,5100"].Substring(5));
            }

            //if (tags.ContainsKey("0020,000D"))
            //    data.AddElementWithValueString(DcmTags.ContrastBolusStopTime, DateTime.Now.ToString());
            //if (tags.ContainsKey("0020,000E"))
            //    data.AddElementWithValueString(DcmTags.ContrastBolusStopTime, DateTime.Now.ToString());
            if (tags.ContainsKey("0020,0010"))
            {
                data.AddElementWithValueString(DcmTags.StudyID, tags["0020,0010"].Substring(5));
            }
            if (tags.ContainsKey("0020,0011"))
            {
                data.AddElementWithValueString(DcmTags.SeriesNumber, tags["0020,0011"].Substring(5));
            }
            if (tags.ContainsKey("0020,0012"))
            {
                data.AddElementWithValueString(DcmTags.AccessionNumber, tags["0020,0012"].Substring(5));
            }
            if (tags.ContainsKey("0020,0013"))
            {
                data.AddElementWithValueString(DcmTags.InstanceNumber, tags["0020,0013"].Substring(5));
            }
            if (tags.ContainsKey("0020,0032"))
            {
                data.AddElementWithValueString(DcmTags.ImagePositionPatient, tags["0020,0032"].Substring(5));
            }
            if (tags.ContainsKey("0020,0037"))
            {
                data.AddElementWithValueString(DcmTags.ImageOrientationPatient, tags["0020,0037"].Substring(5));
            }
            if (tags.ContainsKey("0020,0052"))
            {
                data.AddElementWithValueString(DcmTags.FrameOfReferenceUID, tags["0020,0052"].Substring(5));
            }
            if (tags.ContainsKey("0020,1040"))
            {
                data.AddElementWithValueString(DcmTags.PositionReferenceIndicator, tags["0020,1040"].Substring(5));
            }
            if (tags.ContainsKey("0020,1041"))
            {
                data.AddElementWithValueString(DcmTags.SliceLocation, tags["0020,1041"].Substring(5));
            }
            if (tags.ContainsKey("0020,4000"))
            {
                data.AddElementWithValueString(DcmTags.ImageComments, tags["0020,4000"].Substring(5));
            }



            //data.AddElementWithValueString(DcmTags.StudyTime, DateTime.Now.ToString());
            //data.AddElementWithValueString(DcmTags.AccessionNumber, "");
            //data.AddElementWithValueString(DcmTags.ReferringPhysiciansName, "");
            //data.AddElementWithValueString(DcmTags.StudyID, "1");
            //data.AddElementWithValueString(DcmTags.SeriesNumber, "1");
            //data.AddElementWithValueString(DcmTags.ModalitiesInStudy, "CT");//CR
            //data.AddElementWithValueString(DcmTags.Modality, "CT");//CR
            //data.AddElementWithValueString(DcmTags.NumberOfStudyRelatedInstances, "1");
            //data.AddElementWithValueString(DcmTags.NumberOfStudyRelatedSeries, "1");
            //data.AddElementWithValueString(DcmTags.NumberOfSeriesRelatedInstances, "1");
            //data.AddElementWithValueString(DcmTags.PatientOrientation, "HFS");//F/A
            //data.AddElementWithValueString(DcmTags.ImageLaterality, "U");
            if (tags.ContainsKey("0028,1050"))
            {
                data.AddElementWithValueString(DcmTags.WindowCenter, "1113");
            }
            if (tags.ContainsKey("0028,1051"))
            {
                data.AddElementWithValueString(DcmTags.WindowWidth, "749");
            }
            //data.AddElementWithValueString(DcmTags.WindowCenterWidthExplanation, "WINDOW1\\WINDOW2");
            data.AddElementWithValueString(DcmTags.PixelRepresentation, "0");
            data.AddElementWithValueString(DcmTags.RescaleIntercept, "0");//0
            data.AddElementWithValueString(DcmTags.RescaleSlope, "1");
            //data.AddElementWithValueString(DcmTags.RotationDirection, "CW");
            //ushort bitdepth = 2;未使用过

            DcmPixelData pixelData = new DcmPixelData(DcmTS.ImplicitVRLittleEndian);

            pixelData.PixelRepresentation = 0;//ok
            pixelData.ImageWidth          = imgwidth;
            pixelData.ImageHeight         = imgheight;

            pixelData.SamplesPerPixel = 1;  //ok
            pixelData.HighBit         = 15; //ok
            pixelData.BitsStored      = 16; //ok
            pixelData.BitsAllocated   = 16; //ok
            //pixelData.SamplesPerPixel = 1;
            //pixelData.HighBit = 7;
            //pixelData.BitsStored = 8;
            //pixelData.BitsAllocated = 8;
            pixelData.ImageType = "ORIGINAL\\PRIMARY\\AXIAL";
            pixelData.PhotometricInterpretation = "MONOCHROME2";//2 byte gray? //ok

            //pixelData.FragmentSize
            //pixelData.IsLossy = true;
            //pixelData.LossyCompressionMethod = "01";
            pixelData.PixelDataElement = DcmElement.Create(DcmTags.PixelData, DcmVR.OW); //OB: Other Byte, OW: Other Word

            //pixelData.AddFrame(bmpBytes);
            pixelData.AddFrame(greybytes);

            pixelData.UpdateDataset(data);
            DicomFileFormat ff = new DicomFileFormat(data);

            //string fileout = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "greyimg_test.dcm");
            ff.Save(fileout, Dicom.DicomWriteOptions.Default);//Default
            ff = null;
            return(fileout);
        }