private static IByteBuffer ReadJsonInlineBinary(JsonReader reader)
        {
            reader.Read();
            if (reader.TokenType != JsonToken.String)
            {
                throw new JsonReaderException("Malformed DICOM json");
            }
            var data = new MemoryByteBuffer(System.Convert.FromBase64String(reader.Value as string));

            reader.Read();
            return(data);
        }
Esempio n. 2
0
        public override void Decode(
            DicomPixelData oldPixelData,
            DicomPixelData newPixelData,
            DicomCodecParams parameters)
        {
            for (var frame = 0; frame < oldPixelData.NumberOfFrames; frame++)
            {
                var rleData = oldPixelData.GetFrame(frame);

                // Create new frame data of even length
                var frameSize = newPixelData.UncompressedFrameSize;
                if ((frameSize & 1) == 1)
                {
                    ++frameSize;
                }

                var frameData = new MemoryByteBuffer(new byte[frameSize]);

                var pixelCount       = oldPixelData.Width * oldPixelData.Height;
                var numberOfSegments = oldPixelData.BytesAllocated * oldPixelData.SamplesPerPixel;

                var decoder = new RLEDecoder(rleData);

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

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

                    int pos, offset;

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

                    pos += newPixelData.BytesAllocated - sabyte - 1;
                    decoder.DecodeSegment(s, frameData, pos, offset);
                }

                newPixelData.AddFrame(frameData);
            }
        }
Esempio n. 3
0
        public void UpdateData(PixelData pixelData)
        {
            var buffer = new MemoryByteBuffer(pixelData.Data);

            if (pixelData.BPP <= 16)
            {
                var pd = DicomPixelDataFactory.CreateGrayData(pixelData.Width, pixelData.Height, pixelData.BPP);
                pd.AddFrame(buffer);
                _originalDicomImage = new DicomImage(pd.Dataset);
                _image = _originalDicomImage.RenderImage();
                Image  = _image.AsWriteableBitmap();
            }
        }
Esempio n. 4
0
        private static IByteBuffer ReadJsonInlineBinary(JToken token)
        {
            if (token is JArray array)
            {
                token = array.First();
            }
            if (token.Type != JTokenType.String)
            {
                throw new JsonReaderException("Malformed DICOM json");
            }
            var data = new MemoryByteBuffer(Convert.FromBase64String(token.Value <string>()));

            return(data);
        }
Esempio n. 5
0
        private void AddGreyscaleImage(Bitmap bitmap, int index)
        {
            if (_currentFilmBox == null)
            {
                throw new InvalidOperationException("Start film box first!");
            }

            if (index < 0 || index > _currentFilmBox.BasicImageBoxes.Count)
            {
                // ReSharper disable once NotResolvedInText
                throw new ArgumentOutOfRangeException("Image box index out of range");
            }

            if (bitmap.PixelFormat != PixelFormat.Format24bppRgb &&
                bitmap.PixelFormat != PixelFormat.Format32bppArgb &&
                bitmap.PixelFormat != PixelFormat.Format32bppRgb
                )
            {
                throw new ArgumentException("Not supported bitmap format");
            }

            var dataset = new DicomDataset
            {
                { DicomTag.Columns, (ushort)bitmap.Width },
                { DicomTag.Rows, (ushort)bitmap.Height }
            };

            var pixelData = DicomPixelData.Create(dataset, true);

            pixelData.BitsStored                = 8;
            pixelData.BitsAllocated             = 8;
            pixelData.SamplesPerPixel           = 1;
            pixelData.HighBit                   = 7;
            pixelData.PixelRepresentation       = (ushort)PixelRepresentation.Unsigned;
            pixelData.PlanarConfiguration       = (ushort)PlanarConfiguration.Interleaved;
            pixelData.PhotometricInterpretation = PhotometricInterpretation.Monochrome1;

            var pixels = GetGreyBytes(bitmap);
            var buffer = new MemoryByteBuffer(pixels.Data);

            pixelData.AddFrame(buffer);

            var imageBox = _currentFilmBox.BasicImageBoxes[index];

            imageBox.ImageSequence = dataset;
            imageBox.Polarity      = Polarity;

            pixels.Dispose();
        }
Esempio n. 6
0
        public void RegisterNewEncoding()
        {
            DicomEncoding.RegisterEncoding("KOI 8", "koi8-r");
            var ds = new DicomDataset
            {
                new DicomCodeString(DicomTag.SpecificCharacterSet, "KOI 8"),
            };
            // Грозный^Иван encoded in KOI-8
            var         koi8Name    = new byte[] { 0xe7, 0xd2, 0xcf, 0xda, 0xce, 0xd9, 0xca, 0x5e, 0xe9, 0xd7, 0xc1, 0xce };
            IByteBuffer buffer      = new MemoryByteBuffer(koi8Name);
            var         patientName = new DicomPersonName(DicomTag.PatientName, ds.GetEncodingsForSerialization(), buffer);

            ds.Add(patientName);

            Assert.Equal("Грозный^Иван", ds.GetString(DicomTag.PatientName));
        }
Esempio n. 7
0
        public void GetByteRange_WithOffset_ToEnd_ShouldReturnValidArray(int offset, int count)
        {
            // Arrange
            var bytes    = new byte[] { 1, 2, 3, 4, 5, 6, 7 };
            var buffer   = new MemoryByteBuffer(bytes);
            var expected = bytes.Skip(offset).Take(count).ToArray();

            // Act
            var range = new byte[count];

            buffer.GetByteRange(offset, count, range);

            // Assert
            Assert.Equal(count, range.Length);
            Assert.Equal(expected, range);
        }
Esempio n. 8
0
        public void GetByteRange_WhenBufferIsSmallerThanRequestedCount_Throws()
        {
            // Arrange
            var bytes1              = Enumerable.Repeat((byte)1, 10).ToArray();
            var bytes2              = Enumerable.Repeat((byte)2, 10).ToArray();
            var bytes3              = Enumerable.Repeat((byte)3, 10).ToArray();
            var memoryByteBuffer1   = new MemoryByteBuffer(bytes1);
            var memoryByteBuffer2   = new MemoryByteBuffer(bytes2);
            var memoryByteBuffer3   = new MemoryByteBuffer(bytes3);
            var compositeByteBuffer = new CompositeByteBuffer(memoryByteBuffer1, memoryByteBuffer2, memoryByteBuffer3);

            // Act + Assert
            var actual = new byte[10];

            Assert.Throws <ArgumentException>(() => compositeByteBuffer.GetByteRange(0, 20, actual));
        }
Esempio n. 9
0
        public static void ImportImage(Bitmap img, String id, String name, String birthDate, String gender, String path)
        {
            Bitmap bitmap = img;

            byte[]           pixels  = GetPixels(bitmap);
            MemoryByteBuffer buffer  = new MemoryByteBuffer(pixels);
            DicomDataset     dataset = new DicomDataset();

            //FillDataset(dataset);
            dataset.Add(DicomTag.PhotometricInterpretation, PhotometricInterpretation.Rgb.Value);
            dataset.Add(DicomTag.Rows, (ushort)bitmap.Height);
            dataset.Add(DicomTag.Columns, (ushort)bitmap.Width);
            dataset.Add(DicomTag.BitsAllocated, (ushort)8);
            dataset.Add(DicomTag.SOPClassUID, "1.2.840.10008.5.1.4.1.1.2");
            dataset.Add(DicomTag.SOPInstanceUID, "1.2.840.10008.5.1.4.1.1.2.20181120090837121314");

            DicomPixelData pixelData = DicomPixelData.Create(dataset, true);

            pixelData.BitsStored = 8;
            //pixelData.BitsAllocated = 8;
            pixelData.SamplesPerPixel     = 3;
            pixelData.HighBit             = 7;
            pixelData.PixelRepresentation = 0;
            pixelData.PlanarConfiguration = 0;
            pixelData.AddFrame(buffer);

            dataset.Add(DicomTag.PatientID, id);
            dataset.Add(DicomTag.PatientName, name);
            dataset.Add(DicomTag.PatientBirthDate, birthDate);
            dataset.Add(DicomTag.PatientSex, gender);
            dataset.Add(DicomTag.StudyDate, DateTime.Now);
            dataset.Add(DicomTag.StudyTime, DateTime.Now);
            dataset.Add(DicomTag.AccessionNumber, string.Empty);
            dataset.Add(DicomTag.ReferringPhysicianName, string.Empty);
            dataset.Add(DicomTag.StudyID, "1");
            dataset.Add(DicomTag.SeriesNumber, "1");
            dataset.Add(DicomTag.ModalitiesInStudy, "CR");
            dataset.Add(DicomTag.Modality, "CR");
            dataset.Add(DicomTag.NumberOfStudyRelatedInstances, "1");
            dataset.Add(DicomTag.NumberOfStudyRelatedSeries, "1");
            dataset.Add(DicomTag.NumberOfSeriesRelatedInstances, "1");

            DicomFile dicomfile = new DicomFile(dataset);

            dicomfile.Save(@path);
            //dicomfile.Save(@"D:\STUDIA\6 semestr\InformatykaWMedycynie\Projekt1\DANE\test2.dcm");
        }
Esempio n. 10
0
        public void CopyToStream_ShouldWorkCorrectly()
        {
            // Arrange
            var bytes        = new byte[] { 1, 2, 3, 4, 5, 6, 7 };
            var memoryBuffer = new MemoryByteBuffer(bytes);

            using var ms = new MemoryStream(7);
            var expected = bytes;

            // Act
            memoryBuffer.CopyToStream(ms);
            var actual = ms.ToArray();

            // Assert
            Assert.Equal(expected.Length, actual.Length);
            Assert.Equal(expected, actual);
        }
Esempio n. 11
0
        public void SingleByteCodeExtensions(string encodingName, string expectedName, byte[] rawData)
        {
            var ds = new DicomDataset
            {
                // empty first encoding defaults to ASCII
                new DicomCodeString(DicomTag.SpecificCharacterSet, $"\\{encodingName}"),
            };

            // combine ASCII text with text encoded with another single byte encoding
            // and use the respective code extension
            var         asciiPart = new byte[] { 0x41, 0x53, 0x43, 0x49, 0x49 }; // "ASCII"
            IByteBuffer buffer    = new MemoryByteBuffer(asciiPart.Concat(rawData).ToArray());

            var patientName = new DicomPersonName(DicomTag.PatientName, ds.GetEncodingsForSerialization(), buffer);

            ds.Add(patientName);
            Assert.Equal("ASCII" + expectedName, ds.GetString(DicomTag.PatientName));
        }
Esempio n. 12
0
        public void All_VRs_should_have_one_and_only_one_matching_DicomElement_subclasses()
        {
            var codes = new Collection <string>();
            var types =
                Assembly.GetAssembly(typeof(DicomElement))
                .GetTypes()
                .Where(t => (t.IsSubclassOf(typeof(DicomElement)) || t == typeof(DicomSequence)) && !t.IsAbstract);

            var mbb = new MemoryByteBuffer(new byte[0]);

            foreach (var type in types)
            {
                DicomItem item;
                var       ctor = type.GetConstructor(new[] { typeof(DicomTag), typeof(IByteBuffer) });
                if (ctor != null)
                {
                    item = (DicomItem)ctor.Invoke(new object[] { new DicomTag(0, 0), mbb });
                }
                else
                {
                    ctor = type.GetConstructor(new[] { typeof(DicomTag), typeof(Encoding), typeof(IByteBuffer) });
                    if (ctor != null)
                    {
                        item = (DicomItem)ctor.Invoke(new object[] { new DicomTag(0, 0), Encoding.ASCII, mbb });
                    }
                    else
                    {
                        ctor = type.GetConstructor(new[] { typeof(DicomTag), typeof(DicomDataset[]) });

                        Assert.NotNull(ctor);

                        item = (DicomItem)ctor.Invoke(new object[] { new DicomTag(0, 0), new DicomDataset[0] });
                    }
                }

                Assert.DoesNotContain(item.ValueRepresentation.Code, codes);
                codes.Add(item.ValueRepresentation.Code);
            }

            foreach (var vr in AllVRs)
            {
                Assert.Contains(vr, codes);
            }
        }
Esempio n. 13
0
        public async Task CopyToStreamAsync_ShouldWorkCorrectly()
        {
            // Arrange
            var bytes        = new byte[] { 1, 2, 3, 4, 5, 6, 7 };
            var memoryBuffer = new MemoryByteBuffer(bytes);
            var expected     = bytes;

            using var ms = new MemoryStream(7);

            // Act
            await memoryBuffer.CopyToStreamAsync(ms, CancellationToken.None).ConfigureAwait(false);

            var actual = ms.ToArray();


            // Assert
            Assert.Equal(expected.Length, actual.Length);
            Assert.Equal(expected, actual);
        }
Esempio n. 14
0
        private void insertFrame()
        {
            try
            {
                var result = bmDialog.ShowDialog();
                if (result == DialogResult.OK)
                {
                    var bitmap = new Bitmap(bmDialog.FileName);
                    if (bitmap.Width != img.Width || bitmap.Height != img.Height)
                    {
                        result = MessageBox.Show($"The size of selected image is not matched with current frame sequence, continue inserting?\nImage source: {bitmap.Width}x{bitmap.Height}\nFrame sequence: {img.Width}x{img.Height}", PROGRAM_NAME, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (result == DialogResult.Yes)
                        {
                            result = MessageBox.Show("Scale image to fit the frame sequence?\nIf choose no, the frame will looks strange.", PROGRAM_NAME, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                            if (result == DialogResult.Yes)
                            {
                                bitmap = ImageUtil.ResizeImage(bitmap, img.Width, img.Height);
                            }
                        }
                        else
                        {
                            return;
                        }
                    }

                    byte[] pixels = ImageUtil.GetPixels(bitmap);

                    //TODO: very bad perfomance, needs improvement
                    var fileDecode = file.Clone(DicomTransferSyntax.ExplicitVRLittleEndian);
                    var pixelData  = DicomPixelData.Create(fileDecode.Dataset);
                    var buffer     = new MemoryByteBuffer(pixels);
                    pixelData.AddFrame(buffer);
                    file = fileDecode.Clone(file.Dataset.InternalTransferSyntax);

                    initImage();
                    initFrameList();
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Image invaild, insertion failed.", PROGRAM_NAME, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Gets a byte buffer of specified length from the current position and moves to subsequent position.
        /// </summary>
        /// <param name="count">Number of bytes to read.</param>
        /// <returns>Byte buffer containing the read bytes.</returns>
        public IByteBuffer GetBuffer(uint count)
        {
            IByteBuffer buffer = null;

            if (count == 0)
            {
                buffer = EmptyBuffer.Value;
            }
            else if (count >= this.LargeObjectSize)
            {
                buffer = new StreamByteBuffer(_stream, _stream.Position, count);
                _stream.Seek((int)count, SeekOrigin.Current);
            }
            else
            {
                buffer = new MemoryByteBuffer(GetBytes((int)count));
            }
            return(buffer);
        }
Esempio n. 16
0
        public void Data_CompareWithInitializer_ExactMatch()
        {
            // Arrange
            var bytes1              = Enumerable.Repeat((byte)1, 10).ToArray();
            var bytes2              = Enumerable.Repeat((byte)2, 10).ToArray();
            var bytes3              = Enumerable.Repeat((byte)3, 10).ToArray();
            var memoryByteBuffer1   = new MemoryByteBuffer(bytes1);
            var memoryByteBuffer2   = new MemoryByteBuffer(bytes2);
            var memoryByteBuffer3   = new MemoryByteBuffer(bytes3);
            var compositeByteBuffer = new CompositeByteBuffer(memoryByteBuffer1, memoryByteBuffer2, memoryByteBuffer3);
            var expected            = bytes1.Concat(bytes2).Concat(bytes3).ToArray();

            // Act
            var actual = compositeByteBuffer.Data;

            // Assert
            Assert.Equal(expected.Length, actual.Length);
            Assert.Equal(expected, actual);
        }
Esempio n. 17
0
        public void EndianByteBuffer_GetByteRange_ReturnsCorrectData()
        {
            var bigEndianArray    = new byte[] { 0x00, 0xFF };
            var littleEndianArray = bigEndianArray.Reverse().ToArray();
            var memoryBuffer      = new MemoryByteBuffer(bigEndianArray.ToArray());
            var endianArray       = EndianByteBuffer.Create(memoryBuffer, Endian.Big, 2);

            var first = endianArray.GetByteRange(0, 2).ToArray();

            Assert.Equal(bigEndianArray, memoryBuffer.Data); // buffer data altered

            var second = endianArray.GetByteRange(0, 2).ToArray();

            Assert.Equal(bigEndianArray, memoryBuffer.Data); // buffer data altered

            Assert.Equal(first, littleEndianArray);          // first call wrong endian
            Assert.Equal(second, littleEndianArray);         // second call wrong endian
            Assert.Equal(first, second);                     // first not equal second
        }
Esempio n. 18
0
        private void AddGreyscaleImage(Bitmap bitmap, int index)
        {
            if (_currentFilmBox == null)
            {
                throw new InvalidOperationException("Start film box first!");
            }
            if (index < 0 || index > _currentFilmBox.BasicImageBoxes.Count)
            {
                throw new ArgumentOutOfRangeException(nameof(index), "Image box index out of range");
            }

            if (bitmap.PixelFormat != PixelFormat.Format24bppRgb && bitmap.PixelFormat != PixelFormat.Format32bppArgb &&
                bitmap.PixelFormat != PixelFormat.Format32bppRgb)
            {
                throw new ArgumentException("Not supported bitmap format", nameof(bitmap));
            }

            var dataset = new DicomDataset();

            dataset.Add <ushort>(DicomTag.Columns, (ushort)bitmap.Width)
            .Add <ushort>(DicomTag.Rows, (ushort)bitmap.Height)
            .Add <ushort>(DicomTag.BitsAllocated, 8)
            .Add <ushort>(DicomTag.BitsStored, 8)
            .Add <ushort>(DicomTag.HighBit, 7)
            .Add(DicomTag.PixelRepresentation, (ushort)PixelRepresentation.Unsigned)
            .Add(DicomTag.PlanarConfiguration, (ushort)PlanarConfiguration.Interleaved)
            .Add <ushort>(DicomTag.SamplesPerPixel, 1)
            .Add(DicomTag.PhotometricInterpretation, PhotometricInterpretation.Monochrome2.Value);

            var pixelData = DicomPixelData.Create(dataset, true);

            var pixels = GetGreyBytes(bitmap);
            var buffer = new MemoryByteBuffer(pixels.Data);

            pixelData.AddFrame(buffer);

            var imageBox = _currentFilmBox.BasicImageBoxes[index];

            imageBox.ImageSequence = dataset;

            pixels.Dispose();
        }
Esempio n. 19
0
        public void ReplacementCharactersUsedForBadEncoding()
        {
            var ds = new DicomDataset
            {
                new DicomCodeString(DicomTag.SpecificCharacterSet, "ISO IR 192"),
            };
            var logCollector = NewLogCollector();
            // not a valid UTF-8 encoding
            var         badName     = new byte[] { 0xc4, 0xe9, 0xef, 0xed, 0xf5, 0xf3, 0xe9, 0xef, 0xf2 };
            IByteBuffer buffer      = new MemoryByteBuffer(badName);
            var         patientName = new DicomPersonName(DicomTag.PatientName, ds.GetEncodingsForSerialization(), buffer);

            ds.Add(patientName);
            Assert.Equal("���������", ds.GetString(DicomTag.PatientName));
            Assert.Equal(1, logCollector.NumberOfWarnings);
            var expectedMessage =
                "Could not decode string '���������' with given encoding, using replacement characters.";

            Assert.Equal(expectedMessage, logCollector.WarningAt(0));
        }
Esempio n. 20
0
        public void GetByteRange_CompareWithInitializer_ExactMatch(int offset, int count)
        {
            // Arrange
            var bytes1              = Enumerable.Repeat((byte)1, 10).ToArray();
            var bytes2              = Enumerable.Repeat((byte)2, 10).ToArray();
            var bytes3              = Enumerable.Repeat((byte)3, 10).ToArray();
            var memoryByteBuffer1   = new MemoryByteBuffer(bytes1);
            var memoryByteBuffer2   = new MemoryByteBuffer(bytes2);
            var memoryByteBuffer3   = new MemoryByteBuffer(bytes3);
            var compositeByteBuffer = new CompositeByteBuffer(memoryByteBuffer1, memoryByteBuffer2, memoryByteBuffer3);
            var expected            = bytes1.Concat(bytes2).Concat(bytes3).Skip(offset).Take(count).ToArray();

            // Act
            var actual = new byte[count];

            compositeByteBuffer.GetByteRange(offset, count, actual);

            // Assert
            Assert.Equal(expected.Length, actual.Length);
            Assert.Equal(expected, actual);
        }
Esempio n. 21
0
        public void CopyToStream_ShouldWorkCorrectly()
        {
            // Arrange
            var bytes1              = Enumerable.Repeat((byte)1, 10).ToArray();
            var bytes2              = Enumerable.Repeat((byte)2, 10).ToArray();
            var bytes3              = Enumerable.Repeat((byte)3, 10).ToArray();
            var memoryByteBuffer1   = new MemoryByteBuffer(bytes1);
            var memoryByteBuffer2   = new MemoryByteBuffer(bytes2);
            var memoryByteBuffer3   = new MemoryByteBuffer(bytes3);
            var compositeByteBuffer = new CompositeByteBuffer(memoryByteBuffer1, memoryByteBuffer2, memoryByteBuffer3);
            var expected            = bytes1.Concat(bytes2).Concat(bytes3).ToArray();

            using var ms = new MemoryStream(new byte[30]);

            // Act
            compositeByteBuffer.CopyToStream(ms);
            var actual = ms.ToArray();

            // Assert
            Assert.Equal(expected.Length, actual.Length);
            Assert.Equal(expected, actual);
        }
Esempio n. 22
0
        /// <summary>
        /// Constructs a fake image of dimensions {w,h} with the given 2 byte per pixel data. Encodes and decodes
        /// that data using the given Transfer Syntax on a fake 16 bit CT image and checks the data has not changed.
        /// </summary>
        /// <param name="w">The w.</param>
        /// <param name="h">The h.</param>
        /// <param name="data">The data.</param>
        /// <param name="syntax">The syntax.</param>
        private void CheckData(int w, int h, byte[] data, DicomTransferSyntax syntax)
        {
            var memoryBB = new MemoryByteBuffer(data);
            var ds       = new DicomDataset(DicomTransferSyntax.ExplicitVRLittleEndian);

            ds.AddOrUpdate(DicomVR.IS, DicomTag.Rows, h);
            ds.AddOrUpdate(DicomVR.IS, DicomTag.Columns, w);
            ds.AddOrUpdate(DicomVR.IS, DicomTag.BitsAllocated, 16);
            ds.AddOrUpdate(DicomVR.IS, DicomTag.BitsStored, 16);
            ds.AddOrUpdate(DicomVR.IS, DicomTag.HighBit, 15);
            ds.AddOrUpdate(DicomVR.IS, DicomTag.PixelRepresentation, 1);
            ds.AddOrUpdate(DicomVR.CS, DicomTag.PhotometricInterpretation, "MONOCHROME2");
            ds.AddOrUpdate(DicomVR.IS, DicomTag.SamplesPerPixel, 1);
            var pixelData = DicomPixelData.Create(ds, true);

            pixelData.AddFrame(memoryBB);

            var ds2    = ds.Clone(syntax);
            var dsOrig = ds2.Clone(DicomTransferSyntax.ExplicitVRLittleEndian);

            var origPixData  = DicomPixelData.Create(ds);
            var origPixData2 = DicomPixelData.Create(dsOrig);

            var byteBuffer  = origPixData.GetFrame(0);
            var byteBuffer2 = origPixData2.GetFrame(0);

            var bytes1 = byteBuffer.Data;
            var bytes2 = byteBuffer2.Data;

            var pixelCount  = origPixData.Width * origPixData.Height;
            var pixelCount2 = origPixData2.Width * origPixData2.Height;

            Assert.Equal(pixelCount, pixelCount2);

            for (var i = 0; i < pixelCount * 2; i++)
            {
                Assert.Equal(bytes1[i], bytes2[i]);
            }
        }
Esempio n. 23
0
        public void ExportImage(Bitmap bitmap, string path)
        {
            bitmap = GetValidImage(bitmap);
            int rows, columns;
            byte[] pixels = GetPixels(bitmap, out rows, out columns);
            MemoryByteBuffer buffer = new MemoryByteBuffer(pixels);
            DicomDataset dataset = new DicomDataset();
            FillDataset(dataset);
            dataset.Add(DicomTag.PhotometricInterpretation, PhotometricInterpretation.Rgb.Value);
            dataset.Add(DicomTag.Rows, (ushort)rows);
            dataset.Add(DicomTag.Columns, (ushort)columns);
            dataset.AddOrUpdate(DicomTag.BitsAllocated, (ushort)8);
            DicomPixelData pixelData = DicomPixelData.Create(dataset, true);
            pixelData.BitsStored = 8;
            pixelData.BitsAllocated = 8;
            pixelData.SamplesPerPixel = 3;
            pixelData.HighBit = 7;
            pixelData.PixelRepresentation = 0;
            pixelData.PlanarConfiguration = 0;
            pixelData.AddFrame(buffer);

            DicomFile dicomfile = new DicomFile(dataset);
            dicomfile.Save(path);
        }
        public override void Decode(DicomPixelData oldPixelData, DicomPixelData newPixelData, DicomCodecParams parameters)
        {
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                throw new InvalidOperationException("Unsupported OS Platform");
            }

            for (int frame = 0; frame < oldPixelData.NumberOfFrames; frame++)
            {
                IByteBuffer jpegData = oldPixelData.GetFrame(frame);

                //Converting photmetricinterpretation YbrFull or YbrFull422 to RGB
                if (oldPixelData.PhotometricInterpretation == PhotometricInterpretation.YbrFull)
                {
                    jpegData = PixelDataConverter.YbrFullToRgb(jpegData);
                    oldPixelData.PhotometricInterpretation = PhotometricInterpretation.Rgb;
                }
                else if (oldPixelData.PhotometricInterpretation == PhotometricInterpretation.YbrFull422)
                {
                    jpegData = PixelDataConverter.YbrFull422ToRgb(jpegData, oldPixelData.Width);
                    oldPixelData.PhotometricInterpretation = PhotometricInterpretation.Rgb;
                }

                PinnedByteArray jpegArray = new PinnedByteArray(jpegData.Data);

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

                PinnedByteArray frameArray = new PinnedByteArray(frameData);

                JlsParameters jls = new JlsParameters();

                char[] errorMessage = new char[256];

                // IMPORT JpegLsDecode
                unsafe
                {
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    {
                        CharlsApiResultType err = JpegLSDecode_Linux64((void *)frameArray.Pointer, frameData.Length, (void *)jpegArray.Pointer, Convert.ToUInt32(jpegData.Size), ref jls, errorMessage);
                    }
                    else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        CharlsApiResultType err = JpegLSDecode_Windows64((void *)frameArray.Pointer, frameData.Length, (void *)jpegArray.Pointer, Convert.ToUInt32(jpegData.Size), ref jls, errorMessage);
                    }
                    else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                    {
                        CharlsApiResultType err = JpegLSDecode_MacOS((void *)frameArray.Pointer, frameData.Length, (void *)jpegArray.Pointer, Convert.ToUInt32(jpegData.Size), ref jls, errorMessage);
                    }

                    IByteBuffer buffer;
                    if (frameData.Length >= (1 * 1024 * 1024) || oldPixelData.NumberOfFrames > 1)
                    {
                        buffer = new TempFileBuffer(frameData);
                    }
                    else
                    {
                        buffer = new MemoryByteBuffer(frameData);
                    }
                    buffer = EvenLengthBuffer.Create(buffer);

                    newPixelData.AddFrame(buffer);
                }
            }
        }
Esempio n. 25
0
        public static void MakeEachDicominFolder(string ImageFileFolder)
        {
            List <string> dirs         = new List <string>(Directory.EnumerateDirectories(ImageFileFolder));
            StringBuilder PATIENT_ID   = new StringBuilder();
            StringBuilder PATIENT_NAME = new StringBuilder();
            StringBuilder PATIENT_SEX  = new StringBuilder();
            StringBuilder PATIENT_BOD  = new StringBuilder();
            StringBuilder STUDY_DATE   = new StringBuilder();
            StringBuilder STUDY_TIME   = new StringBuilder();
            StringBuilder STUDY_DESC   = new StringBuilder();
            StringBuilder ACCESSION_NO = new StringBuilder();
            StringBuilder ORDER_CODE   = new StringBuilder();
            StringBuilder FILE_CNT     = new StringBuilder();
            StringBuilder REQUEST      = new StringBuilder();
            StringBuilder SEND_RESULT  = new StringBuilder();

            foreach (string dir in dirs)
            {
                string   existSettingIniStr = dir + @"\info.ini";
                FileInfo fileInfo           = new FileInfo(existSettingIniStr);
                if (!fileInfo.Exists)
                {
                    Form1.lb1.Items.Add("infoINI not exist : " + dir + "[" + DateTime.Now + "]");
                    continue;
                }
                //Example : GetPrivateProfileString("WookoaSetting", "TopAlways", "", topAlways, topAlways.Capacity, "C:\\info.ini");
                //Example : WritePrivateProfileString("WookoaSetting", "ViewTray", "false", "C:\\info.ini");
                //not need dirs name
                GetPrivateProfileString("INFO", "PATIENT_ID", "", PATIENT_ID, PATIENT_ID.Capacity, dir + @"\info.ini");
                GetPrivateProfileString("INFO", "PATIENT_NAME", "", PATIENT_NAME, PATIENT_NAME.Capacity, dir + @"\info.ini");
                GetPrivateProfileString("INFO", "PATIENT_SEX", "", PATIENT_SEX, PATIENT_SEX.Capacity, dir + @"\info.ini");
                GetPrivateProfileString("INFO", "PATIENT_BOD", "", PATIENT_BOD, PATIENT_BOD.Capacity, dir + @"\info.ini");
                GetPrivateProfileString("INFO", "STUDY_DATE", "", STUDY_DATE, STUDY_DATE.Capacity, dir + @"\info.ini");
                GetPrivateProfileString("INFO", "STUDY_TIME", "", STUDY_TIME, STUDY_TIME.Capacity, dir + @"\info.ini");
                GetPrivateProfileString("INFO", "STUDY_DESC", "", STUDY_DESC, STUDY_DESC.Capacity, dir + @"\info.ini");
                GetPrivateProfileString("INFO", "ACCESSION_NO", "", ACCESSION_NO, ACCESSION_NO.Capacity, dir + @"\info.ini");
                GetPrivateProfileString("INFO", "ORDER_CODE", "", ORDER_CODE, ORDER_CODE.Capacity, dir + @"\info.ini");
                GetPrivateProfileString("INFO", "FILE_CNT", "", FILE_CNT, FILE_CNT.Capacity, dir + @"\info.ini");
                GetPrivateProfileString("INFO", "REQUEST", "", REQUEST, REQUEST.Capacity, dir + @"\info.ini");
                GetPrivateProfileString("INFO", "SEND_RESULT", "", SEND_RESULT, SEND_RESULT.Capacity, dir + @"\info.ini");

                if (REQUEST.ToString() != "1")
                {
                    Form1.lb1.Items.Add("Request num is : " + REQUEST.ToString() + "[" + DateTime.Now + "]");
                    continue;
                }
                if (SEND_RESULT.ToString() == "O")
                {
                    Form1.lb1.Items.Add("Already dcm sended : " + dir + "[" + DateTime.Now + "]");
                    continue;
                }

                List <string> imgFiles = new List <string>(Directory.EnumerateFiles(dir));
                List <string> tmp      = new List <string>();

                DicomUID studyuid  = GenerateUid();
                DicomUID seriesuid = GenerateUid();

                DicomUID sopclassid = DicomUID.SecondaryCaptureImageStorage;

                int totalImages = 0; // 폴더 내의 총 이미지 갯수
                int imgindex    = 0; // 시리즈 내의 이미지의 번호를 특정(지금까지 처리된 이미지의 갯수)



                foreach (string imgfile in imgFiles)
                {
                    if ((string.Compare(imgfile.Substring(imgfile.Length - 3, 3), "png") == 0) ||
                        (string.Compare(imgfile.Substring(imgfile.Length - 3, 3), "jpg") == 0))
                    {
                        totalImages++;
                        tmp.Add(imgfile);
                    }
                }

                imgFiles = tmp;

                foreach (string imgfile in imgFiles)
                {
                    DicomDataset dataset = new DicomDataset();

                    DicomUID sopinstanceid = GenerateUid(); //두개 위로 올려야할수도있음

                    FillDataset(dataset,
                                PATIENT_ID.ToString(), PATIENT_NAME.ToString(), PATIENT_SEX.ToString(), PATIENT_BOD.ToString(), STUDY_DATE.ToString(), STUDY_TIME.ToString(), STUDY_DESC.ToString(), ACCESSION_NO.ToString(), ORDER_CODE.ToString()
                                , studyuid, seriesuid, sopclassid, sopinstanceid);                    //TODO : change need priavate profile string

                    dataset.AddOrUpdate(DicomTag.InstanceNumber, Convert.ToString(++imgindex));       // 이미지 번호 (VIEWREX와 UBPACS 모두 이미지 번호를 기준으로 ordering 됨)
                    dataset.AddOrUpdate(DicomTag.ImagesInAcquisition, Convert.ToString(totalImages)); // 검사에서 획득한 이미지의 총합(=Series 내에 속한 Instance 수)

                    bool           imageDataSetFlag = false;
                    DicomPixelData pixelData        = DicomPixelData.Create(dataset, true); //TODO : bug fix dicompixeldata create
                    /////////////////////////////////
                    Bitmap bitmap = new Bitmap(imgfile);
                    // bitmap = GetValidImage(bitmap);
                    int    rows, columns;
                    double ratioCol  = sizeCOL / (double)bitmap.Width;
                    double ratioRow  = sizeROW / (double)bitmap.Height;
                    double ratio     = Math.Min(ratioRow, ratioCol);
                    int    newWidth  = (int)(bitmap.Width * ratio);
                    int    newHeight = (int)(bitmap.Height * ratio);
                    Bitmap newImage  = new Bitmap(sizeCOL, sizeROW);
                    using (Graphics g = Graphics.FromImage(newImage))
                    {
                        g.FillRectangle(Brushes.Black, 0, 0, newImage.Width, newImage.Height);
                        g.DrawImage(bitmap, (sizeCOL - newWidth) / 2, (sizeROW - newHeight) / 2, newWidth, newHeight);
                    }

                    newImage = GetValidImage(newImage);
                    byte[]           pixels = GetPixels(newImage, out rows, out columns);
                    MemoryByteBuffer buffer = new MemoryByteBuffer(pixels);
                    if (imageDataSetFlag == false)
                    {
                        dataset.Add(DicomTag.PhotometricInterpretation, PhotometricInterpretation.Rgb.Value);
                        dataset.Add(DicomTag.Rows, (ushort)sizeROW);
                        dataset.Add(DicomTag.Columns, (ushort)sizeCOL); //TODO : ADD Dcm image count check
                        imageDataSetFlag = true;
                    }
                    pixelData.BitsStored          = 8;
                    pixelData.SamplesPerPixel     = 3; // 3 : red/green/blue  1 : CT/MR Single Grey Scale
                    pixelData.HighBit             = 7;
                    pixelData.PixelRepresentation = 0;
                    pixelData.PlanarConfiguration = 0;

                    //pixelData.NumberOfFrames = imgFiles.Count; // add number of frames.
                    //pixelData.NumberOfFrames = 1;
                    pixelData.AddFrame(buffer); // AddFrame 되면서 Number of Frame은 auto increment됨. 위에서 Number of Frame을 1로 설정할 경우, 아무것도 없는 프레임이 하나 추가됨.
                    //TODO : Need to check if it is created dcm in directory
                    DicomFile dicomfile = new DicomFile(dataset);
                    //string TargetFile = Path.Combine(TargetPath, sopInstanceUID + ".dcm");
                    string TargetFile = Path.Combine(dir, dataset.GetString(DicomTag.SOPInstanceUID) + ".dcm");
                    dicomfile.Save(TargetFile); //todo : dicom file save error

                    try
                    {
                        //SendToPACS(TargetFile, Form1.tb2.Text, Form1.tb3.Text, int.Parse(Form1.tb4.Text), Form1.tb5.Text);

                        DicomFile   m_pDicomFile = DicomFile.Open(TargetFile, DicomEncoding.GetEncoding("ISO 2022 IR 149"));
                        DicomClient pClient      = new DicomClient(Form1.tb3.Text, int.Parse(Form1.tb4.Text), false, Form1.tb2.Text, Form1.tb5.Text);
                        pClient.NegotiateAsyncOps();
                        pClient.AddRequestAsync(new Dicom.Network.DicomCStoreRequest(m_pDicomFile, Dicom.Network.DicomPriority.Medium));
                        pClient.SendAsync();

                        //error event
                        pClient.RequestTimedOut += (object sender, RequestTimedOutEventArgs e) =>
                        {
                            WritePrivateProfileString("INFO", "SEND_RESULT", "X", dir + @"\info.ini");
                            Form1.lb1.Items.Add("Send PACS error exception : " + e.Request + " + " + e.Timeout);
                            throw new NotImplementedException();
                        };


                        WritePrivateProfileString("INFO", "SEND_RESULT", "O", dir + @"\info.ini");
                        Form1.lb1.Items.Add("dcm send finish : " + dir + "[" + DateTime.Now + "]");
                    }
                    catch (Exception e)
                    {
                        WritePrivateProfileString("INFO", "SEND_RESULT", "X", dir + @"\info.ini");
                        Form1.lb1.Items.Add("Send PACS error exception : " + e.Message + " + " + e.StackTrace);
                        Form1.lb1.Items.Add(dir + "[" + DateTime.Now + "]");
                    }
                }
            }
        }
Esempio n. 26
0
        public static void Bmp2Dcm(string bmpPath, string dcmPath, string patient_name, string sex, string age, string process_num, string modality, string hospital_name, string study_description = "", string studydate = "", int TransferSyntax = -1, string sop_uid = "")
        {
            Bitmap bitmap = new Bitmap(bmpPath);

            bitmap = DicomUtility.GetValidImage(bitmap);
            int rows;
            int columns;

            byte[]           pixels   = DicomUtility.GetPixelsForDicom(bitmap, out rows, out columns);
            MemoryByteBuffer buffer   = new MemoryByteBuffer(pixels);
            DicomDataset     dataset  = new DicomDataset();
            Encoding         encoding = Encoding.GetEncoding("GB18030");

            dataset.Add <DicomUID>(DicomTag.SOPClassUID, new DicomUID[]
            {
                DicomUID.SecondaryCaptureImageStorage
            });
            dataset.Add <DicomUID>(DicomTag.StudyInstanceUID, new DicomUID[]
            {
                DicomUtility.GenerateUid()
            });
            dataset.Add <DicomUID>(DicomTag.SeriesInstanceUID, new DicomUID[]
            {
                DicomUtility.GenerateUid()
            });
            dataset.Add <DicomUID>(DicomTag.SOPInstanceUID, new DicomUID[]
            {
                DicomUtility.GenerateUid()
            });
            dataset.Add <string>(DicomTag.PatientID, new string[]
            {
                process_num
            });
            dataset.Add(new DicomItem[]
            {
                DicomUtility.GetDicomItem(DicomTag.PatientName, encoding, patient_name)
            });
            dataset.Add <string>(DicomTag.PatientBirthDate, new string[]
            {
                "00000000"
            });
            dataset.Add(new DicomItem[]
            {
                DicomUtility.GetDicomItem(DicomTag.PatientAge, encoding, age)
            });
            dataset.Add <string>(DicomTag.PatientSex, new string[]
            {
                sex
            });
            if (studydate == "")
            {
                dataset.Add <DateTime>(DicomTag.StudyDate, new DateTime[]
                {
                    DateTime.Now
                });
                dataset.Add <DateTime>(DicomTag.StudyTime, new DateTime[]
                {
                    DateTime.Now
                });
            }
            else
            {
                dataset.Add <string>(DicomTag.StudyDate, new string[]
                {
                    studydate
                });
                dataset.Add <string>(DicomTag.StudyTime, new string[]
                {
                    DateTime.Now.ToString("hhmmssfff")
                });
            }
            dataset.Add <string>(DicomTag.AccessionNumber, new string[]
            {
                string.Empty
            });
            dataset.Add <string>(DicomTag.ReferringPhysicianName, new string[]
            {
                string.Empty
            });
            dataset.Add <string>(DicomTag.StudyID, new string[]
            {
                "1"
            });
            dataset.Add <string>(DicomTag.SeriesNumber, new string[]
            {
                "1"
            });
            dataset.Add <string>(DicomTag.ModalitiesInStudy, new string[]
            {
                modality
            });
            dataset.Add <string>(DicomTag.Modality, new string[]
            {
                modality
            });
            dataset.Add <string>(DicomTag.NumberOfStudyRelatedInstances, new string[]
            {
                "1"
            });
            dataset.Add <string>(DicomTag.NumberOfStudyRelatedSeries, new string[]
            {
                "1"
            });
            dataset.Add <string>(DicomTag.NumberOfSeriesRelatedInstances, new string[]
            {
                "1"
            });
            dataset.Add <string>(DicomTag.PatientOrientation, new string[]
            {
                "F/A"
            });
            dataset.Add <string>(DicomTag.ImageLaterality, new string[]
            {
                "U"
            });
            dataset.Add(new DicomItem[]
            {
                DicomUtility.GetDicomItem(DicomTag.InstitutionName, encoding, hospital_name)
            });
            dataset.Add <string>(DicomTag.StudyDescription, new string[]
            {
                study_description
            });
            dataset.Add <string>(DicomTag.PhotometricInterpretation, new string[]
            {
                PhotometricInterpretation.Rgb.Value
            });
            dataset.Add <ushort>(DicomTag.Rows, new ushort[]
            {
                (ushort)rows
            });
            dataset.Add <ushort>(DicomTag.Columns, new ushort[]
            {
                (ushort)columns
            });
            if (sop_uid != "")
            {
                dataset.Add <string>(DicomTag.SOPInstanceUID, new string[]
                {
                    sop_uid
                });
            }
            DicomPixelData pixelData = DicomPixelData.Create(dataset, true);

            pixelData.BitsStored          = 8;
            pixelData.BitsAllocated       = 8;
            pixelData.SamplesPerPixel     = 3;
            pixelData.HighBit             = 7;
            pixelData.PixelRepresentation = PixelRepresentation.Unsigned;
            pixelData.PlanarConfiguration = PlanarConfiguration.Interleaved;
            pixelData.AddFrame(buffer);
            DicomFile _dicomfile = new DicomFile(dataset);
            DicomFile file       = new DicomFile();

            switch (TransferSyntax)
            {
            case 0:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.JPEG2000Lossless, null);
                goto IL_579;

            case 1:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.RLELossless, null);
                goto IL_579;

            case 2:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.JPEGProcess14, null);
                goto IL_579;

            case 3:
            {
                int bits = _dicomfile.Dataset.Get <int>(DicomTag.BitsAllocated, 0, 8);
                DicomTransferSyntax syntax = DicomTransferSyntax.JPEGProcess1;
                if (bits == 16)
                {
                    syntax = DicomTransferSyntax.JPEGProcess2_4;
                }
                file = _dicomfile.ChangeTransferSyntax(syntax, new DicomJpegParams
                    {
                        Quality = 100
                    });
                goto IL_579;
            }

            case 4:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.ExplicitVRLittleEndian, null);
                goto IL_579;

            case 5:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.ExplicitVRBigEndian, null);
                goto IL_579;

            case 6:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.ImplicitVRLittleEndian, null);
                goto IL_579;

            case 8:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.ImplicitVRBigEndian, null);
                goto IL_579;
            }
            file = _dicomfile;
IL_579:
            file.Save(dcmPath);
        }
Esempio n. 27
0
        /// <summary>
        /// 将BMP文件转换成DICOM文件
        /// </summary>
        /// <param name="file"></param>
        public static void Bmp2Dcm(string bmpPath, string dcmPath, int TransferSyntax = -1, string sop_uid = "")
        {
            Bitmap bitmap = new Bitmap(bmpPath);

            bitmap = GetValidImage(bitmap);
            int rows, columns;

            byte[]           pixels  = GetPixelsForDicom(bitmap, out rows, out columns);
            MemoryByteBuffer buffer  = new MemoryByteBuffer(pixels);
            DicomDataset     dataset = new DicomDataset();

            FillDataset(dataset);
            dataset.Add(DicomTag.PhotometricInterpretation, PhotometricInterpretation.Rgb.Value);
            dataset.Add(DicomTag.Rows, (ushort)rows);
            dataset.Add(DicomTag.Columns, (ushort)columns);
            if (sop_uid != "")
            {
                dataset.Add(DicomTag.SOPInstanceUID, sop_uid);
            }
            DicomPixelData pixelData = DicomPixelData.Create(dataset, true);

            pixelData.BitsStored          = 8;
            pixelData.BitsAllocated       = 8;
            pixelData.SamplesPerPixel     = 3;
            pixelData.HighBit             = 7;
            pixelData.PixelRepresentation = 0;
            pixelData.PlanarConfiguration = 0;
            pixelData.AddFrame(buffer);
            DicomFile _dicomfile = new DicomFile(dataset);
            DicomFile file       = new DicomFile();

            switch (TransferSyntax)
            {
            case 0:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.JPEG2000Lossless);
                break;

            case 1:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.RLELossless);
                break;

            case 2:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.JPEGProcess14);
                break;

            //JPEG Lossy P1 && P4
            case 3:
                var bits   = _dicomfile.Dataset.Get <int>(DicomTag.BitsAllocated, 0, 8);
                var syntax = DicomTransferSyntax.JPEGProcess1;
                if (bits == 16)
                {
                    syntax = DicomTransferSyntax.JPEGProcess2_4;
                }
                file = _dicomfile.ChangeTransferSyntax(syntax, new DicomJpegParams
                {
                    Quality = 100
                });
                break;

            case 4:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.ExplicitVRLittleEndian);
                break;

            case 5:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.ExplicitVRBigEndian);
                break;

            case 6:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.ImplicitVRLittleEndian);
                break;

            case 8:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.ImplicitVRBigEndian);
                break;

            default:
                file = _dicomfile;
                break;
            }


            file.Save(dcmPath);
        }
Esempio n. 28
0
        public static DicomFile GenerateDicomFile(
            string studyInstanceUid,
            string seriesInstanceUid,
            string sopInstanceUid,
            string sopClassUid,
            int rows,
            int cols,
            TestFileBitDepth bitDepth,
            string transferSyntax,
            bool encode,
            int frames = 1,
            string photometricInterpretation = null)
        {
            DicomTransferSyntax initialTs = DicomTransferSyntax.ExplicitVRLittleEndian;

            if (!encode)
            {
                initialTs = DicomTransferSyntax.Parse(transferSyntax);
            }

            var rand = new Random();

            var dicomFile = new DicomFile(
                new DicomDataset(initialTs)
            {
                { DicomTag.StudyInstanceUID, studyInstanceUid ?? TestUidGenerator.Generate() },
                { DicomTag.SeriesInstanceUID, seriesInstanceUid ?? TestUidGenerator.Generate() },
                { DicomTag.SOPInstanceUID, sopInstanceUid ?? TestUidGenerator.Generate() },
                { DicomTag.SOPClassUID, sopClassUid ?? TestUidGenerator.Generate() },
                { DicomTag.Rows, (ushort)rows },
                { DicomTag.Columns, (ushort)cols },
                { DicomTag.PhotometricInterpretation, photometricInterpretation ?? PhotometricInterpretation.Monochrome2.Value },
                { DicomTag.BitsAllocated, (ushort)bitDepth },
                { DicomTag.WindowWidth, ((bitDepth == TestFileBitDepth.EightBit) ? "256" : "65536") },
                { DicomTag.WindowCenter, ((bitDepth == TestFileBitDepth.EightBit) ? "128" : "32768") },
                { DicomTag.AccessionNumber, rand.Next(11111111, 19999999) },
                { DicomTag.PatientID, TestUidGenerator.Generate() },
            });

            var pixelData = DicomPixelData.Create(dicomFile.Dataset, true);

            pixelData.SamplesPerPixel     = 1;
            pixelData.BitsStored          = (ushort)bitDepth;
            pixelData.HighBit             = (ushort)(bitDepth - 1);
            pixelData.PixelRepresentation = PixelRepresentation.Unsigned;

            for (int i = 0; i < frames; i++)
            {
                var buffer = new MemoryByteBuffer(
                    (bitDepth == TestFileBitDepth.SixteenBit)
                        ? GetBytesFor16BitImage(rows, cols, i)
                        : GetBytesFor8BitImage(rows, cols, i));

                pixelData.AddFrame(buffer);
            }

            if (encode && transferSyntax != DicomTransferSyntax.ExplicitVRLittleEndian.UID.UID)
            {
                var transcoder =
                    new DicomTranscoder(
                        dicomFile.Dataset.InternalTransferSyntax,
                        DicomTransferSyntax.Parse(transferSyntax));
                dicomFile = transcoder.Transcode(dicomFile);
            }

            return(dicomFile);
        }
Esempio n. 29
0
        public override unsafe void Encode(DicomPixelData oldPixelData, DicomPixelData newPixelData, DicomCodecParams parameters)
        {
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                throw new InvalidOperationException("Unsupported OS Platform");
            }

            if ((oldPixelData.PhotometricInterpretation == PhotometricInterpretation.YbrPartial422) ||
                (oldPixelData.PhotometricInterpretation == PhotometricInterpretation.YbrPartial420))
            {
                throw new DicomCodecException("Photometric Interpretation '{0}' not supported by JPEG-LS encoder", oldPixelData.PhotometricInterpretation);
            }
            DicomJpegLsParams jparams = (DicomJpegLsParams)parameters;

            if (jparams == null)
            {
                jparams = (DicomJpegLsParams)GetDefaultParameters();
            }

            //IMPORT JLSPARAMETERS (DLLIMPORT)

            JlsParameters jls = new JlsParameters
            {
                width          = oldPixelData.Width,
                height         = oldPixelData.Height,
                bitsPerSample  = oldPixelData.BitsStored,
                stride         = oldPixelData.BytesAllocated * oldPixelData.Width * oldPixelData.SamplesPerPixel,
                components     = oldPixelData.SamplesPerPixel,
                interleaveMode = oldPixelData.SamplesPerPixel == 1
                    ? CharlsInterleaveModeType.None
                    : oldPixelData.PlanarConfiguration == PlanarConfiguration.Interleaved
                        ? CharlsInterleaveModeType.Sample
                        : CharlsInterleaveModeType.Line,
                colorTransformation = CharlsColorTransformationType.None
            };

            if (TransferSyntax == DicomTransferSyntax.JPEGLSNearLossless)
            {
                jls.allowedLossyError = jparams.AllowedError;
            }

            for (int frame = 0; frame < oldPixelData.NumberOfFrames; frame++)
            {
                IByteBuffer frameData = oldPixelData.GetFrame(frame);

                //Converting photmetricinterpretation YbrFull or YbrFull422 to RGB
                if (oldPixelData.PhotometricInterpretation == PhotometricInterpretation.YbrFull)
                {
                    frameData = PixelDataConverter.YbrFullToRgb(frameData);
                    oldPixelData.PhotometricInterpretation = PhotometricInterpretation.Rgb;
                }
                else if (oldPixelData.PhotometricInterpretation == PhotometricInterpretation.YbrFull422)
                {
                    frameData = PixelDataConverter.YbrFull422ToRgb(frameData, oldPixelData.Width);
                    oldPixelData.PhotometricInterpretation = PhotometricInterpretation.Rgb;
                }

                PinnedByteArray frameArray = new PinnedByteArray(frameData.Data);

                byte[] jpegData = new byte[frameData.Size];

                PinnedByteArray jpegArray    = new PinnedByteArray(jpegData);
                uint            jpegDataSize = 0;

                char[] errorMessage = new char[256];

                // IMPORT JpegLsEncode
                unsafe {
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    {
                        CharlsApiResultType err = JpegLSEncode_Linux64((void *)jpegArray.Pointer, checked ((uint)jpegArray.Count), &jpegDataSize, (void *)frameArray.Pointer, checked ((uint)frameArray.Count), ref jls, errorMessage);
                    }

                    else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        CharlsApiResultType err = JpegLSEncode_Windows64((void *)jpegArray.Pointer, checked ((uint)jpegArray.Count), &jpegDataSize, (void *)frameArray.Pointer, checked ((uint)frameArray.Count), ref jls, errorMessage);
                    }

                    Array.Resize(ref jpegData, (int)jpegDataSize);

                    IByteBuffer buffer;
                    if (jpegDataSize >= (1 * 1024 * 1024) || oldPixelData.NumberOfFrames > 1)
                    {
                        buffer = new TempFileBuffer(jpegData);
                    }
                    else
                    {
                        buffer = new MemoryByteBuffer(jpegData);
                    }
                    buffer = EvenLengthBuffer.Create(buffer);
                    newPixelData.AddFrame(buffer);
                }
            }
        }