コード例 #1
0
ファイル: DicomDumpForm.cs プロジェクト: saeidmh83/mdcm
        private void OnClickPixelDataMD5(object sender, EventArgs e)
        {
            if (_selected == -1)
            {
                return;
            }

            try {
                DicomFileFormat ff = new DicomFileFormat();
                ff.Load(_files[_selected], DicomReadOptions.Default |
                        DicomReadOptions.KeepGroupLengths |
                        DicomReadOptions.DeferLoadingLargeElements |
                        DicomReadOptions.DeferLoadingPixelData);

                DcmPixelData pixels = new DcmPixelData(ff.Dataset);

                if (pixels.NumberOfFrames == 0)
                {
                    MessageBox.Show(this, "No pixel data", "Pixel Data MD5");
                }
                else if (pixels.NumberOfFrames >= 1)
                {
                    MessageBox.Show(this, pixels.ComputeMD5(), String.Format("Pixel Data MD5 [{0} frames]", pixels.NumberOfFrames));
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            } catch {
            }
        }
コード例 #2
0
        public static IPixelData Create(DcmPixelData pixelData, int frame)
        {
            PhotometricInterpretation pi = PhotometricInterpretation.Lookup(pixelData.PhotometricInterpretation);

            if (pi == PhotometricInterpretation.Monochrome1 || pi == PhotometricInterpretation.Monochrome2 || pi == PhotometricInterpretation.PaletteColor)
            {
                if (pixelData.BitsStored <= 8)
                {
                    return(new GrayscalePixelDataU8(pixelData.ImageWidth, pixelData.ImageHeight, pixelData.GetFrameDataU8(frame)));
                }
                else if (pixelData.BitsStored <= 16)
                {
                    if (pixelData.IsSigned)
                    {
                        return(new GrayscalePixelDataS16(pixelData.ImageWidth, pixelData.ImageHeight, pixelData.GetFrameDataS16(frame)));
                    }
                    else
                    {
                        return(new GrayscalePixelDataU16(pixelData.ImageWidth, pixelData.ImageHeight, pixelData.GetFrameDataU16(frame)));
                    }
                }
                else
                {
                    throw new DicomImagingException("Unsupported pixel data value for bits stored: {0}", pixelData.BitsStored);
                }
            }
            else if (pi == PhotometricInterpretation.Rgb || pi == PhotometricInterpretation.YbrFull)
            {
                return(new ColorPixelData24(pixelData.ImageWidth, pixelData.ImageHeight, pixelData.GetFrameDataU8(frame)));
            }
            else
            {
                throw new DicomImagingException("Unsupported pixel data photometric interpretation: {0}", pi.Value);
            }
        }
コード例 #3
0
ファイル: DcmCodecHelper.cs プロジェクト: GMZ/mdcm
        public static void DumpFrameToDisk(DcmDataset data, int frame, string file)
        {
            DcmPixelData pixelData = new DcmPixelData(data);

            byte[] pixels = pixelData.GetFrameDataU8(frame);
            File.WriteAllBytes(file, pixels);
        }
コード例 #4
0
ファイル: IPipeline.cs プロジェクト: xiaotie/mdcm
        public static IPipeline Create(DcmDataset dataset, DcmPixelData pixelData)
        {
            PhotometricInterpretation pi = PhotometricInterpretation.Lookup(pixelData.PhotometricInterpretation);

            if (pi == PhotometricInterpretation.Monochrome1 || pi == PhotometricInterpretation.Monochrome2)
            {
                GenericGrayscalePipeline pipeline = new GenericGrayscalePipeline(pixelData.RescaleSlope, pixelData.RescaleIntercept, pixelData.BitsStored, pixelData.IsSigned);
                if (pi == PhotometricInterpretation.Monochrome1)
                {
                    pipeline.ColorMap = ColorTable.Monochrome1;
                }
                else
                {
                    pipeline.ColorMap = ColorTable.Monochrome2;
                }
                WindowLevel[] wl = WindowLevel.FromDataset(dataset);
                if (wl.Length > 0)
                {
                    pipeline.WindowLevel = wl[0];
                }
                return(pipeline);
            }
            else if (pi == PhotometricInterpretation.Rgb)
            {
                return(new RgbColorPipeline());
            }
            else
            {
                throw new DicomImagingException("Unsupported pipeline photometric interpretation: {0}", pi.Value);
            }
        }
コード例 #5
0
        private void UpdateImageBox(DcmImageBox imageBox, String filename, int index)
        {
            //try
            //{
            var ff = new DicomFileFormat();

            ff.Load(filename, DicomReadOptions.DefaultWithoutDeferredLoading);
            if (ff.Dataset == null)
            {
                return;
            }

            ff.Dataset.ChangeTransferSyntax(DicomTransferSyntax.ImplicitVRLittleEndian, null);

            var pixelData = new DcmPixelData(ff.Dataset);
            var pi        = PhotometricInterpretation.Lookup(pixelData.PhotometricInterpretation);

            // Grayscale only printer?
            if (pi.IsColor && _supportsColorPrinting == false)
            {
                pixelData.Unload();
                return;
            }

            // Color only printer?
            if (pi.IsColor == false && _supportsGrayscalePrinting == false)
            {
                pixelData.Unload();
                return;
            }

            DicomUID        imageBoxSOPClassUID;
            DcmItemSequence seq;
            var             item = new DcmItemSequenceItem();

            pixelData.UpdateDataset(item.Dataset);

            if (pi.IsColor)
            {
                imageBoxSOPClassUID = DicomUID.BasicColorImageBoxSOPClass;
                seq = new DcmItemSequence(DicomTags.BasicColorImageSequence);
            }
            else
            {
                imageBoxSOPClassUID = DicomUID.BasicGrayscaleImageBoxSOPClass;
                seq = new DcmItemSequence(DicomTags.BasicGrayscaleImageSequence);
            }
            seq.AddSequenceItem(item);
            imageBox.Dataset.AddItem(seq);

            pixelData.Unload();

            imageBox.UpdateImageBox(imageBoxSOPClassUID);
            imageBox.ImageBoxPosition = (ushort)index;
            //}
            //catch (Exception)
            //{
            //}
        }
コード例 #6
0
        public void Decode(DcmDataset dataset, DcmPixelData oldPixelData, DcmPixelData newPixelData, DcmCodecParameters parameters)
        {
            DcmRleCodecParameters rleParams = parameters as DcmRleCodecParameters;

            if (rleParams == null)
            {
                rleParams = GetDefaultParameters() as DcmRleCodecParameters;
            }

            int pixelCount       = oldPixelData.ImageWidth * oldPixelData.ImageHeight;
            int numberOfSegments = oldPixelData.BytesAllocated * oldPixelData.SamplesPerPixel;

            byte[] frameData = new byte[newPixelData.UncompressedFrameSize];

            for (int i = 0; i < oldPixelData.NumberOfFrames; i++)
            {
                IList <ByteBuffer> rleData = oldPixelData.GetFrameFragments(i);
                RLEDecoder         decoder = new RLEDecoder(rleData);

                if (decoder.NumberOfSegments != numberOfSegments)
                {
                    throw new DicomCodecException("Unexpected number of RLE segments!");
                }

                for (int s = 0; s < numberOfSegments; s++)
                {
                    int sample = s / newPixelData.BytesAllocated;
                    int sabyte = s % newPixelData.BytesAllocated;

                    int pos, offset;

                    if (newPixelData.PlanarConfiguration == 0)
                    {
                        pos    = sample * newPixelData.BytesAllocated;
                        offset = newPixelData.SamplesPerPixel * newPixelData.BytesAllocated;
                    }
                    else
                    {
                        pos    = sample * newPixelData.BytesAllocated * pixelCount;
                        offset = newPixelData.BytesAllocated;
                    }

                    if (rleParams.ReverseByteOrder)
                    {
                        pos += sabyte;
                    }
                    else
                    {
                        pos += newPixelData.BytesAllocated - sabyte - 1;
                    }

                    decoder.DecodeSegment(s, frameData, pos, offset);
                }

                newPixelData.AddFrame(frameData);
            }
        }
コード例 #7
0
		private void Load(DcmDataset dataset) {
			Dataset = dataset;
			if (Dataset.InternalTransferSyntax.IsEncapsulated)
				Dataset.ChangeTransferSyntax(DicomTransferSyntax.ExplicitVRLittleEndian, null);
			DcmPixelData pixelData = new DcmPixelData(Dataset);
			_pixelData = PixelDataFactory.Create(pixelData, 0);
			_pipeline = PipelineFactory.Create(Dataset, pixelData);
			pixelData.Unload();

			_overlays = DcmOverlayData.FromDataset(Dataset);
		}
コード例 #8
0
ファイル: DicomDumpForm.cs プロジェクト: saeidmh83/mdcm
        private void OnClickExtractPixels(object sender, EventArgs e)
        {
            if (_selected == -1)
            {
                return;
            }

            try {
                DicomFileFormat ff = new DicomFileFormat();
                ff.Load(_files[_selected], DicomReadOptions.Default |
                        DicomReadOptions.KeepGroupLengths |
                        DicomReadOptions.DeferLoadingLargeElements |
                        DicomReadOptions.DeferLoadingPixelData);

                DcmPixelData pixels = new DcmPixelData(ff.Dataset);

                if (pixels.NumberOfFrames == 0)
                {
                    return;
                }
                else if (pixels.NumberOfFrames >= 1)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.RestoreDirectory = true;
                    if (sfd.ShowDialog(this) == DialogResult.OK)
                    {
                        byte[] data = pixels.GetFrameDataU8(0);
                        File.WriteAllBytes(sfd.FileName, data);
                    }
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }
            catch {
            }
        }
コード例 #9
0
        public void Encode(DcmDataset dataset, DcmPixelData oldPixelData, DcmPixelData newPixelData, DcmCodecParameters parameters)
        {
            DcmRleCodecParameters rleParams = parameters as DcmRleCodecParameters;

            if (rleParams == null)
            {
                rleParams = GetDefaultParameters() as DcmRleCodecParameters;
            }

            int pixelCount       = oldPixelData.ImageWidth * oldPixelData.ImageHeight;
            int numberOfSegments = oldPixelData.BytesAllocated * oldPixelData.SamplesPerPixel;

            for (int i = 0; i < oldPixelData.NumberOfFrames; i++)
            {
                RLEEncoder encoder   = new RLEEncoder();
                byte[]     frameData = oldPixelData.GetFrameDataU8(i);

                for (int s = 0; s < numberOfSegments; s++)
                {
                    encoder.NextSegment();

                    int sample = s / oldPixelData.BytesAllocated;
                    int sabyte = s % oldPixelData.BytesAllocated;

                    int pos;
                    int offset;

                    if (newPixelData.PlanarConfiguration == 0)
                    {
                        pos    = sample * oldPixelData.BytesAllocated;
                        offset = numberOfSegments;
                    }
                    else
                    {
                        pos    = sample * oldPixelData.BytesAllocated * pixelCount;
                        offset = oldPixelData.BytesAllocated;
                    }

                    if (rleParams.ReverseByteOrder)
                    {
                        pos += sabyte;
                    }
                    else
                    {
                        pos += oldPixelData.BytesAllocated - sabyte - 1;
                    }

                    for (int p = 0; p < pixelCount; p++)
                    {
                        if (pos >= frameData.Length)
                        {
                            throw new DicomCodecException("");
                        }
                        encoder.Encode(frameData[pos]);
                        pos += offset;
                    }
                    encoder.Flush();
                }

                encoder.MakeEvenLength();

                newPixelData.AddFrame(encoder.GetBuffer());
            }
        }
コード例 #10
0
ファイル: DcmJpegCodec.cs プロジェクト: xiaotie/mdcm
        public void Decode(DcmDataset dataset, DcmPixelData oldPixelData, DcmPixelData newPixelData, DcmCodecParameters parameters)
        {
            if (oldPixelData.NumberOfFrames == 0)
            {
                return;
            }

            // Determine JPEG image precision and assert that the implemented codec supports this precision
            int precision;

            try
            {
                precision = JpegHelper.ScanHeaderForBitDepth(oldPixelData);
            }
            catch (DicomCodecException)
            {
                precision = oldPixelData.BitsStored;
            }
            AssertImagePrecision(precision);

            // Ensure consistency in the new pixel data header
            if (precision > 8)
            {
                newPixelData.BitsAllocated = 16;
            }
            else if (newPixelData.BitsStored <= 8)
            {
                newPixelData.BitsAllocated = 8;
            }

            // Set up new pixel data specifics
            newPixelData.PhotometricInterpretation = newPixelData.PhotometricInterpretation.Equals("YBR_FULL_422") ||
                                                     newPixelData.PhotometricInterpretation.Equals("YBR_PARTIAL_422")
                                                         ? "YBR_FULL"
                                                         : oldPixelData.PhotometricInterpretation;
            if (newPixelData.PhotometricInterpretation.Equals("YBR_FULL"))
            {
                newPixelData.PlanarConfiguration = 1;
            }

            try
            {
                for (int j = 0; j < oldPixelData.NumberOfFrames; ++j)
                {
                    var frameData  = new byte[newPixelData.UncompressedFrameSize];
                    var jpegStream = new MemoryStream(oldPixelData.GetFrameDataU8(j));

                    // Decode JPEG from stream
                    var decoder     = new JpegDecoder(jpegStream);
                    var jpegDecoded = decoder.Decode();
                    var img         = jpegDecoded.Image;

                    // Init Buffer
                    int w = img.Width;
                    int h = img.Height;
                    var pixelsFromJpeg = img.Raster;

                    // Copy FluxJpeg buffer into frame data array

/*
 *                  int comps = pixelsFromJpeg.GetLength(0);
 *                  int preIncr = newPixelData.BytesAllocated - comps;
 *
 *                  if (preIncr < 0)
 *                      throw new InvalidOperationException(
 *                          String.Format("Number of JPEG components: {0} exceeds number of bytes allocated: {1}",
 *                                        comps, newPixelData.BytesAllocated));
 */
                    int i = 0;
                    for (int y = 0; y < h; ++y)
                    {
                        for (int x = 0; x < w; ++x)
                        {
                            var pixel = pixelsFromJpeg[0][x, y];
                            frameData[i++] = (byte)((pixel >> 8) & 0xff);
                            frameData[i++] = (byte)(pixel & 0xff);
//                            for (int k = 0; k < preIncr; ++k) frameData[i++] = 0xff;
//                            for (int k = 0; k < comps; ++k) frameData[i++] = pixelsFromJpeg[k][x, y];
                        }
                    }

                    oldPixelData.Unload();

                    if (newPixelData.IsPlanar)
                    {
                        DcmCodecHelper.ChangePlanarConfiguration(frameData,
                                                                 frameData.Length / newPixelData.BytesAllocated,
                                                                 newPixelData.BitsAllocated,
                                                                 newPixelData.SamplesPerPixel, 0);
                    }
                    newPixelData.AddFrame(frameData);
                }
            }
            catch (Exception e)
            {
                Debug.Log.Error("Failed to decode JPEG image: {0}, reason: {1}", e.StackTrace, e.Message);
            }
        }
コード例 #11
0
ファイル: DcmJpegCodec.cs プロジェクト: xiaotie/mdcm
 public void Encode(DcmDataset dataset, DcmPixelData oldPixelData, DcmPixelData newPixelData, DcmCodecParameters parameters)
 {
     throw new NotSupportedException("JPEG encoding currently not supported");
 }
コード例 #12
0
        private void DrawImageBox(DcmImageBox imageBox, Graphics graphics, Point position, int width, int height, int dpiX, int dpiY)
        {
            DcmDataset dataset = imageBox.ImageSequence;

            if (!dataset.Contains(DicomTags.PixelData))
            {
                return;
            }

            DcmPixelData pixelData = new DcmPixelData(dataset);

            PinnedIntArray pixelBuffer = null;
            Bitmap         bitmap      = null;

            if (pixelData.SamplesPerPixel == 3)
            {
                pixelBuffer = new PinnedIntArray(pixelData.GetFrameDataS32(0));
                bitmap      = new Bitmap(pixelData.ImageWidth, pixelData.ImageHeight,
                                         pixelData.ImageWidth * sizeof(int), PixelFormat.Format32bppRgb, pixelBuffer.Pointer);
            }
            else
            {
                bool invert = (pixelData.PhotometricInterpretation == "MONOCHROME1");
                if (imageBox.Polarity == "REVERSE")
                {
                    invert = !invert;
                }

                byte[] pixelsOut = null;

                if (pixelData.BitsAllocated == 8)
                {
                    pixelsOut = pixelData.GetFrameDataU8(0);
                }
                else
                {
                    ushort[] pixels = pixelData.GetFrameDataU16(0);
                    pixelsOut = new byte[pixels.Length];
                    double scale = 256.0 / 4096.0;

                    int pixel = 0;
                    for (int y = 0; y < pixelData.ImageHeight; y++)
                    {
                        for (int x = 0; x < pixelData.ImageWidth; x++)
                        {
                            pixelsOut[pixel] = (byte)(pixels[pixel] * scale);
                            pixel++;
                        }
                    }

                    pixels = null;
                }

                bitmap = new Bitmap(pixelData.ImageWidth, pixelData.ImageHeight, PixelFormat.Format8bppIndexed);

                if (invert)
                {
                    ColorTable.Apply(bitmap, ColorTable.Monochrome1);
                }
                else
                {
                    ColorTable.Apply(bitmap, ColorTable.Monochrome2);
                }

                BitmapData bmData = bitmap.LockBits(new Rectangle(0, 0, pixelData.ImageWidth, pixelData.ImageHeight),
                                                    ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);

                IntPtr pos = bmData.Scan0;
                for (int i = 0, c = pixelsOut.Length; i < c; i += bmData.Width)
                {
                    Marshal.Copy(pixelsOut, i, pos, bmData.Width);
                    pos = new IntPtr(pos.ToInt64() + bmData.Stride);
                }

                bitmap.UnlockBits(bmData);
            }

            //bitmap.SetResolution(dpiX, dpiY);

            int border = 3;

            double factor = Math.Min((double)height / (double)bitmap.Height,
                                     (double)width / (double)bitmap.Width);

            int drawWidth  = (int)(bitmap.Width * factor) - (border * 2);
            int drawHeight = (int)(bitmap.Height * factor) - (border * 2);

            int drawX = position.X + ((width - drawWidth) / 2);
            int drawY = position.Y + ((height - drawHeight) / 2);

            graphics.DrawImage(bitmap, drawX, drawY, drawWidth, drawHeight);
        }
コード例 #13
0
        /// <summary>
        /// Scan header of JPEG image to determine image bit depth
        /// </summary>
        /// <param name="pixelData"></param>
        /// <returns></returns>
        /// <remarks>C# translation of corresponding managed C++ method in JpegHelper.h in the Dicom.Codec(64) project.
        /// Original C++ implementation (probably) emanates from OFFIS DCMTK, djcodecd.cxx</remarks>
        public static int ScanHeaderForBitDepth(DcmPixelData pixelData)
        {
            ByteBuffer   buffer = pixelData.PixelDataSequence.Fragments[0];
            MemoryStream ms     = buffer.Stream;
            BinaryReader br     = EndianBinaryReader.Create(ms, Endian.Big);

            long length = ms.Length;

            while (ms.Position < length)
            {
                ushort marker = br.ReadUInt16();
                switch (marker)
                {
                case 0xffc0:     // SOF_0: JPEG baseline
                case 0xffc1:     // SOF_1: JPEG extended sequential DCT
                case 0xffc2:     // SOF_2: JPEG progressive DCT
                case 0xffc3:     // SOF_3: JPEG lossless sequential
                case 0xffc5:     // SOF_5: differential (hierarchical) extended sequential, Huffman
                case 0xffc6:     // SOF_6: differential (hierarchical) progressive, Huffman
                case 0xffc7:     // SOF_7: differential (hierarchical) lossless, Huffman
                    ms.Seek(2, SeekOrigin.Current);
                    return(br.ReadByte());

                case 0xffc8:     // Reserved for JPEG extentions
                    ms.Seek(br.ReadUInt16() - 2, SeekOrigin.Current);
                    break;

                case 0xffc9:     // SOF_9: extended sequential, arithmetic
                case 0xffca:     // SOF_10: progressive, arithmetic
                case 0xffcb:     // SOF_11: lossless, arithmetic
                case 0xffcd:     // SOF_13: differential (hierarchical) extended sequential, arithmetic
                case 0xffce:     // SOF_14: differential (hierarchical) progressive, arithmetic
                case 0xffcf:     // SOF_15: differential (hierarchical) lossless, arithmetic
                    ms.Seek(2, SeekOrigin.Current);
                    return(br.ReadByte());

                case 0xffc4:     // DHT
                case 0xffcc:     // DAC
                    ms.Seek(br.ReadUInt16() - 2, SeekOrigin.Current);
                    break;

                case 0xffd0:     // RST m
                case 0xffd1:
                case 0xffd2:
                case 0xffd3:
                case 0xffd4:
                case 0xffd5:
                case 0xffd6:
                case 0xffd7:
                case 0xffd8:     // SOI
                case 0xffd9:     // EOI
                    break;

                case 0xffda:     // SOS
                case 0xffdb:     // DQT
                case 0xffdc:     // DNL
                case 0xffdd:     // DRI
                case 0xffde:     // DHP
                case 0xffdf:     // EXP
                case 0xffe0:     // APPn
                case 0xffe1:
                case 0xffe2:
                case 0xffe3:
                case 0xffe4:
                case 0xffe5:
                case 0xffe6:
                case 0xffe7:
                case 0xffe8:
                case 0xffe9:
                case 0xffea:
                case 0xffeb:
                case 0xffec:
                case 0xffed:
                case 0xffee:
                case 0xffef:
                case 0xfff0:     // JPGn
                case 0xfff1:
                case 0xfff2:
                case 0xfff3:
                case 0xfff4:
                case 0xfff5:
                case 0xfff6:
                case 0xfff7:
                case 0xfff8:
                case 0xfff9:
                case 0xfffa:
                case 0xfffb:
                case 0xfffc:
                case 0xfffd:
                case 0xfffe:     // COM
                    ms.Seek(br.ReadUInt16() - 2, SeekOrigin.Current);
                    break;

                case 0xff01:     // TEM
                    break;

                default:
                    int b1 = br.ReadByte();
                    int b2 = br.ReadByte();
                    if (b1 == 0xff && b2 > 2 && b2 <= 0xbf)     // RES reserved markers
                    {
                        break;
                    }
                    throw new DicomCodecException("Unable to determine bit depth: JPEG syntax error!");
                }
            }
            throw new DicomCodecException("Unable to determine bit depth: no JPEG SOF marker found!");
        }
コード例 #14
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);
        }