Example #1
0
        internal DICOMData CreateSearchData()
        {
            DICOMData data = new DICOMData();

            if (FindLevel == QRLevelType.Patient)
            {
                data[DICOMTags.QueryRetrieveLevel].Data = "PATIENT";
            }
            else if (FindLevel == QRLevelType.Study)
            {
                data[DICOMTags.QueryRetrieveLevel].Data = "STUDY";
            }
            else if (FindLevel == QRLevelType.Series)
            {
                data[DICOMTags.QueryRetrieveLevel].Data = "SERIES";
            }
            else if (FindLevel == QRLevelType.Image)
            {
                data[DICOMTags.QueryRetrieveLevel].Data = "IMAGE";
            }
            else
            {
                data[DICOMTags.QueryRetrieveLevel].Data = "STUDY";  //fallback...
            }
            foreach (uint tag in SearchTerms.Keys)
            {
                data[tag].Data = SearchTerms[tag];
            }
            return(data);
        }
Example #2
0
        private void _sendImage(PSImage image, Stream outputStream, BinaryWriter writer)
        {
            var transferSyntax = TransferSyntaxes.Lookup(image.TransferSyntaxID);

            if (transferSyntax.Compression != DICOMSharp.Data.Compression.CompressionInfo.None)
            {
                // Need to decompress
                var data = new DICOMData();
                data.ParseFile(PSUtils.GetParsedFilePath(image.Path), true, PSUtils.GetLogger());
                data.Uncompress();

                var memStream = new MemoryStream();
                data.WriteToStreamAsPart10File(memStream, PSUtils.GetLogger());

                writer.Write((UInt32)(memStream.Length + 4));
                memStream.Position = 0;
                memStream.CopyTo(outputStream);
            }
            else
            {
                // Write the file out directly.
                var fileInfo = new FileInfo(PSUtils.GetParsedFilePath(image.Path));
                var size     = fileInfo.Length;
                writer.Write((UInt32)(size + 4));
                fileInfo.OpenRead().CopyTo(outputStream);
            }
        }
Example #3
0
        public static void RoundTripAndRender()
        {
            foreach (FileInfo fi in new DirectoryInfo("..\\CompressionSamples").GetFiles("*.dcm"))
            {
                Console.WriteLine("Compression Test -- Filename: " + fi.Name);

                DICOMData data = new DICOMData();
                data.ParseFile(fi.FullName, true, new NullLogger());
                TransferSyntax syntax = data.TransferSyntax;

                int compressedLength = (int)data[DICOMTags.PixelData].GetDataLength(false);

                data.Uncompress();

                Image testImage = DICOMQuickRenderer.QuickRender(data, 0);
                Assert.IsNotNull(testImage);

                int uncompressedLength = (int)data[DICOMTags.PixelData].GetDataLength(false);
                Assert.IsTrue(uncompressedLength > compressedLength);

                if (CompressionWorker.SupportsCompression(syntax.Compression))
                {
                    data.ChangeTransferSyntax(syntax);
                    int recompressedLength = (int)data[DICOMTags.PixelData].GetDataLength(false);
                    Assert.IsTrue(recompressedLength < uncompressedLength);
                }

                //data.WriteFile(fi.FullName.Replace(".dcm", "_un.dcm"));
            }
        }
        internal static Bitmap QuickRender(DICOMData data, int frameNum, bool calcWL, short window, short level)
        {
            RenderAssistant assistant = new RenderAssistant();

            assistant.SetSource(data);

            if (calcWL)
            {
                assistant.CalculateWindowLevel(frameNum);
            }
            else
            {
                assistant.Window = window;
                assistant.Level  = level;
            }

            ushort imWidth  = (ushort)data.Elements[DICOMTags.ImageWidth].Data;
            ushort imHeight = (ushort)data.Elements[DICOMTags.ImageHeight].Data;

            assistant.Resize(new Size(imWidth, imHeight));

            assistant.RenderFrame(frameNum, true);

            return(assistant.RenderedImage);
        }
Example #5
0
        /// <summary>
        /// This will generate a deep folder structure filename for a DICOMData.  The returned format is:
        /// [Study Instance UID]\[Series Instance UID]\[4 digit zero-padded image Instance Number]_[MD5 hash of the SOP Instance UID].dcm
        /// </summary>
        /// <param name="data">The DICOM dataset to generate the filename for.</param>
        /// <param name="logger">A logger to return errors attempting to generate a filename.</param>
        /// <returns></returns>
        public static string GenerateFilenameFromImage(DICOMData data, ILogger logger)
        {
            string studyUID = data[DICOMTags.StudyInstanceUID].Display;

            if (studyUID == "")
            {
                logger.Log(LogLevel.Warning, "Image has no Study Instance UID.  Can not generate filename...");
                return(null);
            }

            string seriesUID = data[DICOMTags.SeriesInstanceUID].Display;

            if (seriesUID == "")
            {
                logger.Log(LogLevel.Warning, "Image has no Series Instance UID.  Can not generate filename...");
                return(null);
            }

            string instanceUID = data[DICOMTags.SOPInstanceUID].Display;

            if (instanceUID == "")
            {
                logger.Log(LogLevel.Warning, "Image has no SOP Instance UID.  Can not generate filename...");
                return(null);
            }

            //form full file path
            string finalPath = studyUID + "\\";

            finalPath += seriesUID + "\\";

            string instanceStr = "UNK";

            if (data.Elements.ContainsKey(DICOMTags.InstanceNumber))
            {
                string imageInstanceStr = data[DICOMTags.InstanceNumber].Display;
                if (!string.IsNullOrEmpty(imageInstanceStr))
                {
                    int instanceNum = 0;
                    if (int.TryParse(imageInstanceStr, out instanceNum))
                    {
                        instanceStr = instanceNum.ToString().PadLeft(4, '0');
                    }
                }
            }

            finalPath += instanceStr + "_";

            byte[] md5instance = new MD5CryptoServiceProvider().ComputeHash(
                Encoding.ASCII.GetBytes(instanceUID));
            finalPath += StringUtil.MakeByteHexString(md5instance) + ".dcm";

            return(finalPath);
        }
Example #6
0
        public SequenceItemWrapper(DICOMData <DICOMObject> seqItems)
        {
            _seqItems    = seqItems;
            internalList = new List <T>();

            foreach (var item in _seqItems.MultipicityValue)
            {
                internalList.Add(new T()
                {
                    DCM = item
                });
            }
        }
Example #7
0
        private void listener_StoreRequest(DICOMConnection conn, DICOMData data)
        {
            try
            {
                if (!this._settings.StoreMetadataOnlyFiles && !data.Elements.ContainsKey(DICOMTags.PixelData))
                {
                    this._logger.Log(LogLevel.Info, "Data set has no image data (only metadata). Metadata storing is disabled, so image will not be persisted.");
                    conn.SendCSTORERSP(CommandStatus.Error_MissingAttribute);
                    return;
                }

                if (this._settings.AutoDecompress && data.TransferSyntax.Compression != DICOMSharp.Data.Compression.CompressionInfo.None)
                {
                    this._logger.Log(LogLevel.Info, "Image is compressed, decompressing before storage!");
                    if (!data.Uncompress())
                    {
                        this._logger.Log(LogLevel.Warning, "Image decompression failed! Storing compressed image.");
                    }
                }

                string postName = FileUtil.GenerateFilenameFromImage(data, this._logger);

                //form full file path
                string diskPath = _db.FixImagePath(this._settings.ImageStoragePath);
                if (!diskPath.EndsWith("\\"))
                {
                    diskPath += "\\";
                }
                diskPath += postName;

                data.WriteFile(diskPath, this._logger);

                // Db path can save a ~ path, so recalc without MapPath
                string dbPath = this._settings.ImageStoragePath;
                if (!dbPath.EndsWith("\\"))
                {
                    dbPath += "\\";
                }
                dbPath += postName;

                this._db.PersistImage(data, diskPath, dbPath);

                conn.SendCSTORERSP(CommandStatus.Success);
            }
            catch (Exception e)
            {
                this._logger.Log(LogLevel.Error, "Error in StoreRequest: " + e.ToString());
                conn.SendCSTORERSP(CommandStatus.Error_UnrecognizedOperation);
            }
        }
Example #8
0
 public void AttachImage(DICOMData indata)
 {
     try
     {
         if (indata.Elements.ContainsKey(DICOMTags.PixelData))
         {
             simpleViewerPane1.AddImage(indata);
         }
     }
     catch (Exception)
     {
     }
     Application.DoEvents();
 }
Example #9
0
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                DICOMData loadedData = new DICOMData();
                loadedData.ParseFile(openFileDialog1.FileName, true, new NullLogger());
                loadedData.Uncompress();

                if (loadedData.Elements.ContainsKey(DICOMTags.PixelData))
                {
                    viewer.AddImage(loadedData);
                }
            }
        }
Example #10
0
        /// <summary>
        /// Add a new DICOMData to the set of contained images.  If this is the first image added, it will automatically
        /// select it and render it.
        /// </summary>
        /// <param name="data">The DICOMData to add.</param>
        public void AddImage(DICOMData data)
        {
            dataList.Add(data);
            if (dataList.Count == 1)
            {
                assistant.SetSource(data);
                //ScrollImages(1);

                //Calculate first W/L
                if (!manualWindowLevel)
                {
                    assistant.CalculateWindowLevel(frameNum);
                }
            }
            Invalidate();
        }
Example #11
0
        static void TestThumbnails()
        {
            foreach (FileInfo fi in new DirectoryInfo("..\\CompressionSamples").GetFiles("*.dcm"))
            //foreach (FileInfo fi in new DirectoryInfo("..\\CompressionSamples").GetFiles("JPEG-LS Lossless.dcm"))
            {
                Console.WriteLine("Compression Test -- Filename: " + fi.Name);

                DICOMData data = new DICOMData();
                data.ParseFile(fi.FullName, true, new NullLogger());
                //data.Uncompress();
                //data.WriteFile(fi.FullName.Replace(".dcm", "_un.dcm"));

                Image testImage = DICOMQuickRenderer.QuickRender(data, 0);

                testImage.Save(fi.FullName.Replace(".dcm", ".png"), ImageFormat.Png);
            }
        }
Example #12
0
        internal void AddResponseRow(DICOMData dataDICOM)
        {
            Dictionary <uint, object> respRow = new Dictionary <uint, object>();

            foreach (DICOMElement elem in dataDICOM.Elements.Values)
            {
                if (elem.Tag == DICOMTags.QueryRetrieveLevel)
                {
                    //ignore!
                }
                else
                {
                    respRow[elem.Tag] = elem.Data;
                }
            }
            ResponseRows.Add(respRow);
        }
 /// <summary>
 /// Writes the multiple binary data objects as one string of bytes
 /// </summary>
 /// <typeparam name="T">the type of data</typeparam>
 /// <param name="data">the data to be converted to binary</param>
 /// <param name="writeSingleFunc">the function that can convert a single data item into bytes</param>
 /// <returns>the concated array of bytes that contains all data items</returns>
 public static byte[] ComposeMultipleBinary <T>(DICOMData <T> data, Func <T, byte[]> writeSingleFunc)
 {
     if (data != null)
     {
         List <byte> bytes = new List <byte>();
         foreach (var datum in data.MultipicityValue)
         {
             //Write one data item
             var single = writeSingleFunc(datum);
             foreach (var byt in single)
             {
                 bytes.Add(byt);
             }
         }
         return(bytes.ToArray());
     }
     return(new byte[0]);
 }
Example #14
0
        private void LoadFile(string FName)
        {
            CurFName = FName;
            CurDCM   = new DICOMData();
            CurDCM.ParseFile(CurFName, true, new NullLogger());

            //StringBuilder builder = new StringBuilder();
            //builder.Append("[\r\n");
            //byte[] data = (byte[])CurDCM.Elements[DICOMTags.PixelData].Data;
            //for (int i=0; i<data.Length; i++)
            //{
            //    builder.Append(data[i]);
            //    if (i < data.Length-1) builder.Append(",");
            //    if ((i & 255) == 0) builder.Append("\r\n");
            //}
            //builder.Append("]\r\n");

            //File.WriteAllText(@"c:\src\test.json", builder.ToString());

            RefreshView();
        }
Example #15
0
        /// <summary>
        /// Attempt to pull an abstract syntax out of a DICOMData.
        /// </summary>
        /// <param name="data">The DICOMData to extract from.</param>
        /// <returns>The abstract syntax from either the media storage Sop class uid field or the sop class uid field.
        /// If both are missing, returns CT Image Storage.</returns>
        public static AbstractSyntax ExtractAbstractSyntaxFromDicomData(DICOMData data)
        {
            var MediaStorageSOPClassUID = data.Elements[DICOMTags.MediaStorageSOPClassUID] as DICOMElementUI;

            if (MediaStorageSOPClassUID != null)
            {
                return(AbstractSyntaxes.Lookup(MediaStorageSOPClassUID.Data as string));
            }
            else
            {
                var SOPClassUID = data.Elements[DICOMTags.SOPClassUID] as DICOMElementUI;
                if (SOPClassUID != null)
                {
                    return(AbstractSyntaxes.Lookup(SOPClassUID.Data as string));
                }
                else
                {
                    // Fall back to basic CT image storage...
                    return(AbstractSyntaxes.CTImageStorage);
                }
            }
        }
Example #16
0
        /// <summary>
        /// Call this function to recursively look through a directory and try to find all valid DICOM files from
        /// that directory.  When it finds one, it will load it (without the image data loaded, for speed reasons)
        /// and pass it through to the <see cref="ImageAddedHandler"/> callback.
        /// </summary>
        /// <param name="baseDir">The directory to start searching in.</param>
        /// <param name="handler">The callback function called with every found/loaded image.</param>
        /// <param name="logger">The logger to use for error/info.</param>
        /// <param name="token">A cancellation token to abort the import.</param>
        public static void ParseAndLoadImagesFromDirectoryRecursively(DirectoryInfo baseDir, ImageAddedHandler handler, ILogger logger, CancellationToken token)
        {
            foreach (DirectoryInfo di2 in baseDir.GetDirectories())
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }

                ParseAndLoadImagesFromDirectoryRecursively(di2, handler, logger, token);
            }

            foreach (FileInfo fi in baseDir.GetFiles())
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }

                try
                {
                    DICOMData data = new DICOMData();
                    if (data.ParseFile(fi.FullName, false, logger))
                    {
                        if (token.IsCancellationRequested)
                        {
                            return;
                        }

                        handler(data, fi.FullName);
                    }
                }
                catch
                {
                }
            }
        }
Example #17
0
 public static byte[] WriteTag(DICOMData <Tag> data)
 {
     //TODO modify to make VM > 1 possible
     return(MultiplicityComposer.ComposeMultipleBinary(data, WriteTagSingle));
 }
Example #18
0
        internal QRRequestData(DICOMData cmd, DICOMData data)
        {
            //parse query-retrieve level
            QueryLevel = AbstractSyntaxes.Lookup((string)cmd[DICOMTags.AffectedSOPClass].Data).ParseQRLevel();

            if (QueryLevel == QueryRetrieveLevel.ModalityWorklist)
            {
                FindLevel = QRLevelType.Study;
            }
            else
            {
                //parse find level
                string type = ((string)data[DICOMTags.QueryRetrieveLevel].Data).Trim().ToUpper();
                if (type == "PATIENT")
                {
                    FindLevel = QRLevelType.Patient;
                }
                else if (type == "STUDY")
                {
                    FindLevel = QRLevelType.Study;
                }
                else if (type == "SERIES")
                {
                    FindLevel = QRLevelType.Series;
                }
                else if (type == "IMAGE")
                {
                    FindLevel = QRLevelType.Image;
                }
                else
                {
                    FindLevel = QRLevelType.Study;    //fallback
                }
            }

            Console.Write(data.Dump());

            //pull all search terms
            SearchTerms = new Dictionary <uint, object>();
            foreach (DICOMElement elem in data.Elements.Values)
            {
                //Don't add group length elements
                if (elem.Elem == 0)
                {
                    continue;
                }
                if (elem.Tag == DICOMTags.QueryRetrieveLevel)
                {
                    continue;
                }

                if (elem.Tag == DICOMTags.ScheduledProcedureStepSequence)
                {
                    if (elem.VRShort == DICOMElementSQ.vrshort)
                    {
                        foreach (SQItem sqItem in ((DICOMElementSQ)elem).Items)
                        {
                            foreach (DICOMElement elemi in sqItem.Elements)
                            {
                                if (elemi.Elem == 0)
                                {
                                    continue;
                                }
                                if (elemi.Tag == DICOMTags.QueryRetrieveLevel)
                                {
                                    continue;
                                }

                                SearchTerms.Add(elemi.Tag, elemi.Data);
                            }
                        }
                    }
                }
                else if (elem.Data.ToString() != "")
                {
                    SearchTerms.Add(elem.Tag, elem.Data);
                }
            }

            FillTagsList(data);
        }
Example #19
0
        private void FillTagsList(DICOMData data)
        {
            //get the tags needed to fill
            TagsToFill = new List <uint>();
            SPSSTags   = new List <uint>();

            //In the spec, PS 9.4, Pages 77-79
            switch (FindLevel)
            {
            case QRLevelType.Patient:
                //Required
                TagsToFill.Add(DICOMTags.PatientName);
                TagsToFill.Add(DICOMTags.PatientID);
                break;

            case QRLevelType.Study:
                //Required Study-level
                TagsToFill.Add(DICOMTags.StudyDate);
                TagsToFill.Add(DICOMTags.StudyTime);
                TagsToFill.Add(DICOMTags.AccessionNumber);
                TagsToFill.Add(DICOMTags.StudyID);
                TagsToFill.Add(DICOMTags.StudyInstanceUID);
                break;

            case QRLevelType.Series:
                //Required series-level
                TagsToFill.Add(DICOMTags.Modality);
                TagsToFill.Add(DICOMTags.SeriesNumber);
                TagsToFill.Add(DICOMTags.SeriesInstanceUID);
                break;

            case QRLevelType.Image:
                //Required image-level
                TagsToFill.Add(DICOMTags.InstanceNumber);
                TagsToFill.Add(DICOMTags.SOPInstanceUID);
                break;
            }

            if (data != null)
            {
                //fill anything else in we don't already have from required
                foreach (DICOMElement elem in data.Elements.Values)
                {
                    if (elem.Elem == 0)
                    {
                        continue;
                    }
                    if (elem.Tag == DICOMTags.QueryRetrieveLevel)
                    {
                        continue;
                    }

                    if (elem.Tag == DICOMTags.ScheduledProcedureStepSequence)
                    {
                        if (elem.VRShort == DICOMElementSQ.vrshort)
                        {
                            foreach (SQItem sqItem in ((DICOMElementSQ)elem).Items)
                            {
                                foreach (DICOMElement elemi in sqItem.Elements)
                                {
                                    if (elemi.Elem == 0)
                                    {
                                        continue;
                                    }
                                    if (elemi.Tag == DICOMTags.QueryRetrieveLevel)
                                    {
                                        continue;
                                    }

                                    SPSSTags.Add(elemi.Tag);
                                }
                            }
                        }
                    }
                    else
                    {
                        TagsToFill.Add(elem.Tag);
                    }
                }
            }
        }
Example #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AbstractElement{T}"/> class.
 /// </summary>
 /// <param name="tag">The tag.</param>
 /// <param name="data">The data.</param>
 public AbstractElement(Tag tag, T data)
 {
     DataContainer             = new DICOMData <T>();
     Tag                       = tag;
     DataContainer.SingleValue = data;
 }
Example #21
0
 public static byte[] WriteUnsignedVeryLong(DICOMData <ulong> data)
 {
     return(MultiplicityComposer.ComposeMultipleBinary(data, WriteUnsignedVeryLongSingle));
 }
 public static byte[] WriteDoublePrecision(DICOMData<double> data)
 {
     return MultiplicityComposer.ComposeMultipleBinary(data, WriteDoublePrecisionSingle);
 }
Example #23
0
        /// <summary>
        /// Sets/changes the DICOMData that the RenderAssistant will be rendering.  Important information about
        /// the image is pre-loaded for faster repeated rendering.
        /// Note: Calling this function does not automatically cause a redraw.
        /// You may also
        /// </summary>
        /// <param name="newData">New DICOMData to draw from (may be null to clear parameters)</param>
        public void SetSource(DICOMData newData)
        {
            if (newData == data)
            {
                return;
            }
            data = newData;

            if (data == null)
            {
                FrameCount = 0;
                return;
            }

            if (!data.Uncompress())
            {
                throw new Exception("Unsupported Compression, can't decompress.");
            }

            if (!data.Elements.ContainsKey(DICOMTags.BitsAllocated))
            {
                throw new MissingMemberException("Missing the Bits Allocated field, can't render.");
            }

            bitsAllocated = (ushort)data.Elements[DICOMTags.BitsAllocated].Data;
            bytes         = (bitsAllocated == 8) ? 1 : 2;

            if (!data.Elements.ContainsKey(DICOMTags.PhotometricInterpretation))
            {
                throw new MissingMemberException("Missing the Photometric Interpretation field, can't render.");
            }

            photoInterp = data.Elements[DICOMTags.PhotometricInterpretation].Display.Trim();
            bFlipMono   = (photoInterp == "MONOCHROME1");
            bRGB        = (photoInterp == "RGB");
            bPalette    = (photoInterp == "PALETTE COLOR");

            if (bPalette)
            {
                if (!data.Elements.ContainsKey(DICOMTags.RedPaletteColorLookupTableData) || !data.Elements.ContainsKey(DICOMTags.GreenPaletteColorLookupTableData) || !data.Elements.ContainsKey(DICOMTags.BluePaletteColorLookupTableData))
                {
                    throw new MissingMemberException("Missing a Palette Lookup field on a PALETTE COLORed image, can't render.");
                }

                palettes = new byte[3][] {
                    (byte[])data.Elements[DICOMTags.RedPaletteColorLookupTableData].Data,
                    (byte[])data.Elements[DICOMTags.GreenPaletteColorLookupTableData].Data,
                    (byte[])data.Elements[DICOMTags.BluePaletteColorLookupTableData].Data
                };

                //PS 3, Page 417-418
                if (!data.Elements.ContainsKey(DICOMTags.RedPaletteColorLookupTableDescriptor) || !data.Elements.ContainsKey(DICOMTags.GreenPaletteColorLookupTableDescriptor) || !data.Elements.ContainsKey(DICOMTags.BluePaletteColorLookupTableDescriptor))
                {
                    throw new MissingMemberException("Missing a Palette Descriptor field on a PALETTE COLORed image, can't render.");
                }
                palette16         = (((ushort[])data.Elements[DICOMTags.RedPaletteColorLookupTableDescriptor].Data)[2] == 16);
                paletteNumEntries = ((ushort[])data.Elements[DICOMTags.RedPaletteColorLookupTableDescriptor].Data)[0];
                if (paletteNumEntries == 0)
                {
                    // Apparently 0 means 65536
                    paletteNumEntries = 65536;
                }
                paletteFirstEntry = ((ushort[])data.Elements[DICOMTags.RedPaletteColorLookupTableDescriptor].Data)[1];
                //figure out supplemental palette color LUT at some point

                if (palette16)
                {
                    // Flip endianness of the palettes
                    palettes16 = new ushort[3][]
                    {
                        new ushort[paletteNumEntries],
                        new ushort[paletteNumEntries],
                        new ushort[paletteNumEntries]
                    };

                    for (int i = 0; i < paletteNumEntries; i++)
                    {
                        palettes16[0][i] = (ushort)(palettes[0][2 * i + 1] | (palettes[0][2 * i] << 8));
                        palettes16[1][i] = (ushort)(palettes[1][2 * i + 1] | (palettes[1][2 * i] << 8));
                        palettes16[2][i] = (ushort)(palettes[2][2 * i + 1] | (palettes[2][2 * i] << 8));
                    }
                }
            }
            else
            {
                palettes   = new byte[3][];
                palettes16 = new ushort[3][];
            }

            bPlanarOne = false;
            if (data.Elements.ContainsKey(DICOMTags.PlanarConfiguration))
            {
                bPlanarOne = ((ushort)data.Elements[DICOMTags.PlanarConfiguration].Data == 1);
            }

            if (!data.Elements.ContainsKey(DICOMTags.ImageWidth))
            {
                throw new MissingMemberException("Missing the Image Width field, can't render.");
            }
            if (!data.Elements.ContainsKey(DICOMTags.ImageHeight))
            {
                throw new MissingMemberException("Missing the Image Height field, can't render.");
            }

            imWidth  = (ushort)data.Elements[DICOMTags.ImageWidth].Data;
            imHeight = (ushort)data.Elements[DICOMTags.ImageHeight].Data;

            signedData = false;
            if (data.Elements.ContainsKey(DICOMTags.PixelRepresentation))
            {
                signedData = Convert.ToInt32(data.Elements[DICOMTags.PixelRepresentation].Data) == 1;
            }

            bRescaling = (data.Elements.ContainsKey(DICOMTags.RescaleIntercept) && data.Elements.ContainsKey(DICOMTags.RescaleSlope));
            adjM       = 1.0f; adjB = 0;
            if (bRescaling)
            {
                adjB = float.Parse((string)data.Elements[DICOMTags.RescaleIntercept].Data);
                adjM = float.Parse((string)data.Elements[DICOMTags.RescaleSlope].Data);
                if (adjB == 0 && adjM == 1.0f)
                {
                    bRescaling = false;
                }
            }

            if (data.Elements.ContainsKey(DICOMTags.PixelIntensityRelationship))
            {
                string intensityRelationship = data.Elements[DICOMTags.PixelIntensityRelationship].Data.ToString().Trim().ToUpperInvariant();
                if (intensityRelationship == "LIN")
                {
                    if (data.Elements.ContainsKey(DICOMTags.PixelIntensityRelationshipSign))
                    {
                        float newAdj = float.Parse(data.Elements[DICOMTags.PixelIntensityRelationshipSign].Data.ToString());
                        if (newAdj == -1)
                        {
                            adjM *= newAdj;

                            ushort bitsStored = (ushort)data.Elements[DICOMTags.BitsStored].Data;
                            if (bitsStored == 16)
                            {
                                adjB += 65536;
                            }
                            else if (bitsStored == 12)
                            {
                                adjB += 4096;
                            }
                            else if (bitsStored == 8)
                            {
                                adjB += 256;
                            }

                            bRescaling = true;
                        }
                    }
                }
            }

            bMultiframe = (data.Elements.ContainsKey(DICOMTags.NumberOfFrames));
            if (bMultiframe)
            {
                FrameCount = int.Parse((string)data.Elements[DICOMTags.NumberOfFrames].Data);
            }
            else
            {
                FrameCount = 1;
            }

            if (!data.Elements.ContainsKey(DICOMTags.PixelData))
            {
                throw new MissingMemberException("Missing the Pixel Data field, can't render.");
            }
            pixelData = data.Elements[DICOMTags.PixelData];
        }
Example #24
0
 public static byte[] WriteTag(DICOMData <Tag> data)
 {
     return(MultiplicityComposer.ComposeMultipleBinary(data, WriteTagSingle));
 }
Example #25
0
 public static byte[] WriteTag(DICOMData<Tag> data)
 {
     return MultiplicityComposer.ComposeMultipleBinary(data, WriteTagSingle);
 }
Example #26
0
        private void conn_CommandReceived(DICOMConnection conn, PDATACommands command, DICOMData cmdDICOM, DICOMData dataDICOM)
        {
            switch (command)
            {
            case PDATACommands.CECHORQ:
                conn.LogLine(LogLevel.Info, "Received C-ECHO-RQ");
                conn.SendCECHORSP();
                break;

            case PDATACommands.CSTORERQ:
                conn.LogLine(LogLevel.Info, "Received C-STORE-RQ");

                //Add source AE title to image
                dataDICOM[DICOMTags.SourceApplicationEntityTitle].Data = conn.CallingAE;

                if (StoreRequest != null)
                {
                    StoreRequest(conn, dataDICOM);
                }
                else
                {
                    conn.SendCSTORERSP(CommandStatus.Success);
                }
                break;

            case PDATACommands.CSTORERSP:
                conn.LogLine(LogLevel.Info, "Received C-STORE-RSP");

                break;

            case PDATACommands.CFINDRQ:
                conn.LogLine(LogLevel.Info, "Received C-FIND-RQ");
                if (FindRequest != null)
                {
                    QRResponseData response = FindRequest(conn, new QRRequestData(cmdDICOM, dataDICOM));
                    conn.SendCFINDRSP(response);
                }
                else
                {
                    conn.SendCFINDRSP(null, CommandStatus.Success);
                }
                break;

            case PDATACommands.CGETRQ:
                conn.LogLine(LogLevel.Info, "Received C-GET-RQ");
                if (GetRequest != null)
                {
                    QRResponseData response = GetRequest(conn, new QRRequestData(cmdDICOM, dataDICOM));
                    conn.StartGetResponse(response);
                }
                else
                {
                    conn.SendCGETRSP((ushort)cmdDICOM[DICOMTags.MessageID].Data, CommandStatus.Success, 0, 0, 0, 0);
                }
                break;

            case PDATACommands.CMOVERQ:
                conn.LogLine(LogLevel.Info, "Received C-MOVE-RQ");
                if (MoveRequest != null)
                {
                    string            newAE  = cmdDICOM[DICOMTags.MoveDestination].Display.Trim();
                    ApplicationEntity entity = null;
                    if (EntityLookup != null)
                    {
                        entity = EntityLookup(newAE);
                    }

                    if (entity != null)
                    {
                        QRResponseData response = MoveRequest(conn, new QRRequestData(cmdDICOM, dataDICOM));
                        conn.StartMoveResponse(entity, response);
                    }
                    else
                    {
                        conn.LogLine(LogLevel.Warning, "No entity found for the MOVE request: " + newAE);
                        conn.SendCMOVERSP(CommandStatus.Error_ProcessingFailure, 0, 0, 0, 0);
                    }
                }
                else
                {
                    conn.SendCMOVERSP(CommandStatus.Error_ProcessingFailure, 0, 0, 0, 0);
                }
                break;

            case PDATACommands.NGETRQ:
                conn.LogLine(LogLevel.Info, "Received N-GET-RQ");

                // No idea what we're supposed to do with these yet
                conn.SendNGETRSP(CommandStatus.Refused_SOPClassNotSupported, null);
                break;

            default:
                conn.LogLine(LogLevel.Warning, "Unhandled P-DATA Command Type: " + command + "...");
                break;
            }
        }
Example #27
0
 public static byte[] WriteSinglePrecision(DICOMData <float> data)
 {
     return(MultiplicityComposer.ComposeMultipleBinary <float>(data, WriteSinglePrecisionSingle));
 }
Example #28
0
 public static byte[] WriteDoublePrecision(DICOMData <double> data)
 {
     return(MultiplicityComposer.ComposeMultipleBinary(data, WriteDoublePrecisionSingle));
 }
 public static byte[] WriteUnsignedLong(DICOMData<uint> data)
 {
     return MultiplicityComposer.ComposeMultipleBinary(data, WriteUnsignedLongSingle);
 }
Example #30
0
 public static byte[] WriteSignedLong(DICOMData <int> data)
 {
     return(MultiplicityComposer.ComposeMultipleBinary(data, WriteSignedLongSingle));
 }
 public static byte[] WriteUnsignedShort(DICOMData<ushort> data)
 {
     return MultiplicityComposer.ComposeMultipleBinary(data, WriteUnsignedShortSingle);
 }
Example #32
0
 public static byte[] WriteUnsignedShort(DICOMData <ushort> data)
 {
     return(MultiplicityComposer.ComposeMultipleBinary(data, WriteUnsignedShortSingle));
 }
 public static byte[] WriteTag(DICOMData<Tag> data)
 {
     //TODO modify to make VM > 1 possible
     return MultiplicityComposer.ComposeMultipleBinary(data, WriteTagSingle);
 }
Example #34
0
 /// <summary>
 /// This function must be overridden to provide handling of received P-DATA commands.
 /// </summary>
 /// <param name="conn">The DICOMConnection in question.</param>
 /// <param name="command">The P-DATA command ID.</param>
 /// <param name="cmdDICOM">The command DICOM set of the P-DATA command.</param>
 /// <param name="dataDICOM">The data DICOM set of the P-DATA command, if any.  Null if no data set contained in the command.</param>
 protected abstract void conn_CommandReceived(DICOMConnection conn, PDATACommands command, DICOMData cmdDICOM, DICOMData dataDICOM);
Example #35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AbstractElement{T}"/> class.
 /// </summary>
 /// <param name="tag">The tag.</param>
 /// <param name="dataArray">The data array.</param>
 public AbstractElement(Tag tag, T[] dataArray)
 {
     DataContainer = new DICOMData <T>();
     Tag           = tag;
     DataContainer = DICOMData <T> .CreateFromArray(dataArray);
 }