Example #1
0
        public static void ConfigureCStoreCommand
        (
            DicomCommand command,
            StoreAddInConfigurationElement storeConfig
        )
        {
            CStoreCommand storeCommand;


            storeCommand = command as CStoreCommand;

            if (null != storeCommand)
            {
                storeCommand.Configuration.DataSetStorageLocation = storeConfig.StorageLocation;
#if (LEADTOOLS_V19_OR_LATER)
                storeCommand.Configuration.HangingProtocolLocation = storeConfig.HangingProtocolLocation;
#endif
                storeCommand.Configuration.OverwriteBackupLocation = storeConfig.OverwriteBackupLocation;
                storeCommand.Configuration.DicomFileExtension      = storeConfig.StoreFileExtension;

                storeCommand.Configuration.DirectoryStructure.CreatePatientFolder = storeConfig.DirectoryStructure.CreatePatientFolder;
                storeCommand.Configuration.DirectoryStructure.CreateSeriesFolder  = storeConfig.DirectoryStructure.CreateSeriesFolder;
                storeCommand.Configuration.DirectoryStructure.CreateStudyFolder   = storeConfig.DirectoryStructure.CreateStudyFolder;
                storeCommand.Configuration.DirectoryStructure.UsePatientName      = storeConfig.DirectoryStructure.UsePatientName;
                storeCommand.Configuration.DirectoryStructure.SplitPatientId      = storeConfig.DirectoryStructure.SplitPatientId;

                foreach (SaveImageFormatElement imageFormatElement in storeConfig.ImagesFormat)
                {
                    SaveImageFormat imageFormat = GetImageFormat(imageFormatElement);

                    storeCommand.Configuration.OtherImageFormat.Add(imageFormat);
                }

                storeCommand.Configuration.SaveThumbnail = storeConfig.CreateThumbnailImage;

                if (storeCommand.Configuration.SaveThumbnail)
                {
                    storeCommand.Configuration.ThumbnailFormat = GetImageFormat(storeConfig.ThumbnailFormat);
                }

#if (LEADTOOLS_V20_OR_LATER)
                storeCommand.Configuration.SaveMetadataOptions.StoreJson     = storeConfig.JsonStore;
                storeCommand.Configuration.SaveMetadataOptions.SaveJsonFlags =
                    (storeConfig.JsonTrimWhiteSpace     ? DicomDataSetSaveJsonFlags.TrimWhiteSpace   : DicomDataSetSaveJsonFlags.None) |
                    (storeConfig.JsonWriteKeyword       ? DicomDataSetSaveJsonFlags.WriteKeyword     : DicomDataSetSaveJsonFlags.None) |
                    (storeConfig.JsonMinify             ? DicomDataSetSaveJsonFlags.Minify           : DicomDataSetSaveJsonFlags.None) |
                    (storeConfig.JsonIgnoreBinaryData   ? DicomDataSetSaveJsonFlags.IgnoreBinaryData : DicomDataSetSaveJsonFlags.None);

                storeCommand.Configuration.SaveMetadataOptions.StoreXml     = storeConfig.XmlStore;
                storeCommand.Configuration.SaveMetadataOptions.SaveXmlFlags =
                    (storeConfig.XmlTrimWhiteSpace      ? DicomDataSetSaveXmlFlags.TrimWhiteSpace       : DicomDataSetSaveXmlFlags.None) |
                    (storeConfig.XmlTrimWhiteSpace      ? DicomDataSetSaveXmlFlags.WriteFullEndElement  : DicomDataSetSaveXmlFlags.None) |
                    (storeConfig.XmlTrimWhiteSpace      ? DicomDataSetSaveXmlFlags.IgnoreBinaryData     : DicomDataSetSaveXmlFlags.IgnoreBinaryData);
                storeCommand.Configuration.SaveMetadataOptions.StoreXml = storeConfig.XmlStore;
#endif // #if (LEADTOOLS_V20_OR_LATER)
            }
        }
Example #2
0
 /// <summary>
 /// Gets an appropiate <see cref="IImageFormat"/> for the given <see cref="SaveImageFormat"/>.
 /// </summary>
 public static IImageFormat GetFormatFor(SaveImageFormat imageFormat)
 {
     return(imageFormat switch
     {
         SaveImageFormat.Png => SixLabors.ImageSharp.Formats.Png.PngFormat.Instance,
         SaveImageFormat.Jpeg => SixLabors.ImageSharp.Formats.Jpeg.JpegFormat.Instance,
         SaveImageFormat.Bmp => SixLabors.ImageSharp.Formats.Bmp.BmpFormat.Instance,
         SaveImageFormat.Gif => SixLabors.ImageSharp.Formats.Gif.GifFormat.Instance,
         _ => throw new ArgumentException("Invalid " + nameof(SaveImageFormat), nameof(imageFormat)),
     });
Example #3
0
        private static SaveImageFormat GetImageFormat
        (
            SaveImageFormatElement imageFormatElement
        )
        {
            SaveImageFormat imageFormat;


            imageFormat               = new SaveImageFormat( );
            imageFormat.Format        = ( RasterImageFormat )Enum.Parse(typeof(RasterImageFormat), imageFormatElement.Format, true);
            imageFormat.Height        = imageFormatElement.Height;
            imageFormat.Width         = imageFormatElement.Width;
            imageFormat.QualityFactor = imageFormatElement.QFactor;

            return(imageFormat);
        }
Example #4
0
        private static SaveImageFormatElement GetImageFormatElement
        (
            SaveImageFormat imageFormat
        )
        {
            SaveImageFormatElement imageFormatElement;


            imageFormatElement = new SaveImageFormatElement( );

            imageFormatElement.Format  = Enum.GetName(typeof(RasterImageFormat), imageFormat.Format);
            imageFormatElement.Height  = imageFormat.Height;
            imageFormatElement.Width   = imageFormat.Width;
            imageFormatElement.QFactor = imageFormat.QualityFactor;

            return(imageFormatElement);
        }
        /// <summary>
        /// Saves this <see cref="Texture1D"/>'s image to a stream.
        /// </summary>
        /// <param name="texture">The <see cref="Texture1D"/> whose image to save.</param>
        /// <param name="stream">The stream to save the texture image to.</param>
        /// <param name="imageFormat">The format the image will be saved as.</param>
        public static void SaveAsImage(this Texture1D texture, Stream stream, SaveImageFormat imageFormat)
        {
            if (texture == null)
            {
                throw new ArgumentNullException(nameof(texture));
            }

            if (stream == null)
            {
                throw new ArgumentException(nameof(stream));
            }

            IImageFormat format = ImageUtils.GetFormatFor(imageFormat);

            using Image <Rgba32> image = new Image <Rgba32>((int)texture.Width, 1);
            texture.GetData(image);
            image.Save(stream, format);
        }
        /// <summary>
        /// Saves this <see cref="Texture2D"/>'s image to a stream. You can't save multisampled textures.
        /// </summary>
        /// <param name="texture">The <see cref="Texture2D"/> whose image to save.</param>
        /// <param name="stream">The stream to save the texture image to.</param>
        /// <param name="imageFormat">The format the image will be saved as.</param>
        /// <param name="flip">Whether to flip the image after the pixels are read.</param>
        public static void SaveAsImage(this Texture2D texture, Stream stream, SaveImageFormat imageFormat, bool flip = false)
        {
            if (texture == null)
            {
                throw new ArgumentNullException(nameof(texture));
            }

            if (texture.Samples != 0)
            {
                throw new NotSupportedException("You can't save multisampled textures");
            }

            if (stream == null)
            {
                throw new ArgumentException("You must specify a stream", nameof(stream));
            }

            IImageFormat format = ImageUtils.GetFormatFor(imageFormat);

            using Image <Rgba32> image = new Image <Rgba32>((int)texture.Width, (int)texture.Height);
            texture.GetData(image, flip);
            image.Save(stream, format);
        }
Example #7
0
 public static bool SaveImageAsText(IupHandle ih, string filename, SaveImageFormat format, string name)
 {
     return(NativeIUP.IupSaveImageAsText(IupHandle.GetCHandle(ih), filename, format.ToString().ToUpper(), name) != 0);
 }
        public HttpResponseMessage Load(Uri uri, int pageNumber = 1, int resolution = 0, string mimeType = null, int bitsPerPixel = 0, int qualityFactor = 0, int imageWidth = 0, int imageHeight = 0)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }
            if (pageNumber < 0)
            {
                throw new ArgumentOutOfRangeException("pageNumber", "must be a value greater than or equal to 0");
            }

            var page = pageNumber;

            // Default is page 1
            if (page == 0)
            {
                page = 1;
            }

            if (resolution < 0)
            {
                throw new ArgumentOutOfRangeException("resolution", "must be a value greater than or equals to 0");
            }

            // Sanity check on other parameters
            if (qualityFactor < 0 || qualityFactor > 100)
            {
                throw new ArgumentOutOfRangeException("qualityFactor", "must be a value between 0 and 100");
            }

            if (imageWidth < 0)
            {
                throw new ArgumentOutOfRangeException("width", "must be a value greater than or equal to 0");
            }
            if (imageHeight < 0)
            {
                throw new ArgumentOutOfRangeException("height", "must be a value greater than or equal to 0");
            }

            // Get the image format
            SaveImageFormat saveFormat = SaveImageFormat.GetFromMimeType(mimeType);

            // Use a temp file, much faster than calling Load/Info from a URI directly
            // In a production service, you might want to create a caching mechanism
            string tempFile = Path.GetTempFileName();

            try
            {
                // Force the uri to be fully qualified, reject everything else for security reasons
                if (uri.IsFile || uri.IsUnc)
                {
                    throw new ArgumentException("URL cannot be local file or UNC path.");
                }

                //Download the file

                try
                {
                    using (WebClient client = new WebClient())
                    {
                        client.DownloadFile(uri, tempFile); // exception occurs when file is used by another process.(getting error code=>500(internal server error))
                    }

                    using (RasterCodecs codecs = new RasterCodecs())
                    {
                        ServiceHelper.InitCodecs(codecs, resolution);

                        // Load the page
                        using (RasterImage image = codecs.Load(tempFile, 0, CodecsLoadByteOrder.BgrOrGray, pageNumber, pageNumber))
                        {
                            // Resize it (will only resize if both width and height are not 0), will also take care of FAX images (with different resolution)
                            ImageResizer.ResizeImage(image, imageWidth, imageHeight);

                            // We need to find out the format, bits/pixel and quality factor
                            // If the user gave as a format, use it
                            if (saveFormat == null)
                            {
                                // If the user did not give us a format, use PNG
                                saveFormat = new PngImageFormat();
                                mimeType   = "image/png";
                            }

                            saveFormat.PrepareToSave(codecs, image, bitsPerPixel, qualityFactor);

                            // Save it to a memory stream
                            MemoryStream        ms       = null;
                            HttpResponseMessage response = null;
                            try
                            {
                                ms = new MemoryStream();
                                codecs.Save(image, ms, saveFormat.ImageFormat, saveFormat.BitsPerPixel);
                                ms.Position = 0;

                                // Set the MIME type and Content-Type if there is a valid web context
                                HttpContext currentContext = HttpContext.Current;
                                if (currentContext != null)
                                {
                                    currentContext.Response.ContentType = mimeType;
                                    currentContext.Response.Headers.Add("ContentLength", ms.Length.ToString());
                                }

                                // If we just return the stream, Web Api will try to serialize it.
                                // If the return type is "HttpResponseMessage" it will not serialize
                                // and you can set the content as you wish.
                                response         = new HttpResponseMessage();
                                response.Content = new StreamContent(ms);
                                return(response);
                            }
                            catch
                            {
                                if (ms != null)
                                {
                                    ms.Dispose();
                                }
                                if (response != null)
                                {
                                    response.Dispose();
                                }
                                throw;
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    return(new HttpResponseMessage());
                }
            }
            catch (Exception ex)
            {
                Log(string.Format("Load - Error:{1}{0}TempFile:{2}{0}Uri:{3}, PageNumber:{4}", Environment.NewLine, ex.Message, tempFile, uri, pageNumber));
                throw;
            }
            finally
            {
                if (File.Exists(tempFile))
                {
                    try
                    {
                        File.Delete(tempFile);
                    }
                    catch { }
                }
            }
        }
        public HttpResponseMessage GetThumbnailsGrid([FromUri] GetThumbnailsGridRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request", "must not be null");
            }

            if (string.IsNullOrEmpty(request.DocumentId))
            {
                throw new ArgumentException("documentId", "must not be null");
            }

            if (request.FirstPageNumber < 0)
            {
                throw new ArgumentException("'firstPageNumber' must be a value greater than or equal to 0");
            }

            var firstPageNumber = request.FirstPageNumber;
            var lastPageNumber  = request.LastPageNumber;

            // Default is page 1 and -1
            if (firstPageNumber == 0)
            {
                firstPageNumber = 1;
            }
            if (lastPageNumber == 0)
            {
                lastPageNumber = -1;
            }

            if (request.Width < 0 || request.Height < 0)
            {
                throw new ArgumentException("'width' and 'height' must be value greater than or equal to 0");
            }
            if (request.MaximumGridWidth < 0)
            {
                throw new ArgumentException("'maximumGridWidth' must be a value greater than or equal to 0");
            }

            // Get the image format
            var saveFormat = SaveImageFormat.GetFromMimeType(request.MimeType);

            // Now load the document
            var cache = ServiceHelper.Cache;

            using (var document = DocumentFactory.LoadFromCache(cache, request.DocumentId))
            {
                DocumentHelper.CheckLoadFromCache(document);

                if (request.Width > 0 && request.Height > 0)
                {
                    document.Images.ThumbnailPixelSize = new LeadSize(request.Width, request.Height);
                }

                using (var image = document.Images.GetThumbnailsGrid(firstPageNumber, lastPageNumber, request.MaximumGridWidth))
                {
                    Stream stream = ImageSaver.SaveImage(image, document.RasterCodecs, saveFormat, request.MimeType, 0, 0);

                    // If we just return the stream, Web Api will try to serialize it.
                    // If the return type is "HttpResponseMessage" it will not serialize
                    // and you can set the content as you wish.
                    var result = new HttpResponseMessage();
                    result.Content = new StreamContent(stream);
                    ServiceHelper.UpdateCacheSettings(result);
                    return(result);
                }
            }
        }
 /// <summary>
 /// Saves this <see cref="Texture2D"/>'s image to a file. You can't save multisampled textures.
 /// If the file already exists, it will be replaced.
 /// </summary>
 /// <param name="texture">The <see cref="Texture2D"/> whose image to save.</param>
 /// <param name="file">The name of the file where the image will be saved.</param>
 /// <param name="imageFormat">The format the image will be saved as.</param>
 /// <param name="flip">Whether to flip the image after the pixels are read.</param>
 public static void SaveAsImage(this Texture2D texture, string file, SaveImageFormat imageFormat, bool flip = false)
 {
     using FileStream fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Read);
     SaveAsImage(texture, fileStream, imageFormat, flip);
 }
 /// <summary>
 /// Saves this <see cref="FramebufferObject"/>'s image to a file. You can't save multisampled framebuffers.<para/>
 /// If the file already exists, it will be replaced.
 /// </summary>
 /// <param name="framebuffer">The <see cref="FramebufferObject"/> whose image to save.</param>
 /// <param name="file">The name of the file where the image will be saved.</param>
 /// <param name="imageFormat">The format the image will be saved as.</param>
 /// <param name="flip">Whether to flip the image after the pixels are read.</param>
 public static void SaveAsImage(this FramebufferObject framebuffer, string file, SaveImageFormat imageFormat, bool flip = false)
 {
     using FileStream fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Read);
     SaveAsImage(framebuffer, fileStream, imageFormat, flip);
 }
        /// <summary>
        /// Saves this <see cref="FramebufferObject"/>'s image to a stream. You can't save multisampled framebuffers.
        /// </summary>
        /// <param name="framebuffer">The <see cref="FramebufferObject"/> whose image to save.</param>
        /// <param name="stream">The stream to save the framebuffer image to.</param>
        /// <param name="imageFormat">The format the image will be saved as.</param>
        /// <param name="flip">Whether to flip the image after the pixels are read.</param>
        public static void SaveAsImage(this FramebufferObject framebuffer, Stream stream, SaveImageFormat imageFormat, bool flip = false)
        {
            if (framebuffer == null)
            {
                throw new ArgumentNullException(nameof(framebuffer));
            }

            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            IImageFormat format = ImageUtils.GetFormatFor(imageFormat);

            using Image <Rgba32> image = new Image <Rgba32>((int)framebuffer.Width, (int)framebuffer.Height);
            framebuffer.ReadPixels(image, flip);
            image.Save(stream, format);
        }
        public HttpResponseMessage GetImage([FromUri] GetImageRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            var pageNumber = request.PageNumber;

            if (string.IsNullOrEmpty(request.DocumentId))
            {
                throw new ArgumentException("documentId must not be null");
            }

            if (pageNumber < 0)
            {
                throw new ArgumentException("'pageNumber' must be a value greater than or equal to 0");
            }

            // Default is page 1
            if (pageNumber == 0)
            {
                pageNumber = 1;
            }

            if (request.Resolution < 0)
            {
                throw new ArgumentException("'resolution' must be a value greater than or equal to 0");
            }

            // Sanity check on other parameters
            if (request.QualityFactor < 0 || request.QualityFactor > 100)
            {
                throw new ArgumentException("'qualityFactor' must be a value between 0 and 100");
            }

            if (request.Width < 0 || request.Height < 0)
            {
                throw new ArgumentException("'width' and 'height' must be value greater than or equal to 0");
            }

            // Get the image format
            var saveFormat = SaveImageFormat.GetFromMimeType(request.MimeType);

            // Now load the document
            var cache = ServiceHelper.Cache;

            using (var document = DocumentFactory.LoadFromCache(cache, request.DocumentId))
            {
                DocumentHelper.CheckLoadFromCache(document);
                DocumentHelper.CheckPageNumber(document, pageNumber);

                var documentPage = document.Pages[pageNumber - 1];
                using (var image = documentPage.GetImage(request.Resolution))
                {
                    // Resize it (will only resize if both width and height are not 0), will also take care of FAX images (with different resolution)
                    ImageResizer.ResizeImage(image, request.Width, request.Height);
                    var stream = ImageSaver.SaveImage(image, document.RasterCodecs, saveFormat, request.MimeType, request.BitsPerPixel, request.QualityFactor);

                    // If we just return the stream, Web Api will try to serialize it.
                    // If the return type is "HttpResponseMessage" it will not serialize
                    // and you can set the content as you wish.
                    var response = new HttpResponseMessage();
                    response.Content = new StreamContent(stream);
                    ServiceHelper.UpdateCacheSettings(response);
                    return(response);
                }
            }
        }
        public HttpResponseMessage GetSvgBackImage([FromUri] GetSvgBackImageRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            var pageNumber = request.PageNumber;

            if (string.IsNullOrEmpty(request.DocumentId))
            {
                throw new ArgumentException("documentId must not be null");
            }

            if (pageNumber < 0)
            {
                throw new ArgumentException("'pageNumber' must be a value greater than or equals to 0");
            }

            // Default is page 1
            if (pageNumber == 0)
            {
                pageNumber = 1;
            }

            if (request.Resolution < 0)
            {
                throw new ArgumentException("'resolution' must be a value greater than or equal to 0");
            }

            // Sanity check on other parameters
            if (request.QualityFactor < 0 || request.QualityFactor > 100)
            {
                throw new ArgumentException("'qualityFactor' must be a value between 0 and 100");
            }

            if (request.Width < 0 || request.Height < 0)
            {
                throw new ArgumentException("'width' and 'height' must be value greater than or equal to 0");
            }

            // Get the image format
            var saveFormat = SaveImageFormat.GetFromMimeType(request.MimeType);

            var rasterBackColor = RasterColor.White;

            if (request.BackColor != null)
            {
                try
                {
                    rasterBackColor = RasterColor.FromHtml(request.BackColor);
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(string.Format("GetImage - Error:{1}{0}documentId:{2} pageNumber:{3}", Environment.NewLine, ex.Message, request.DocumentId, pageNumber), "Error");
                }
            }

            // Now load the document
            var cache = ServiceHelper.Cache;

            using (var document = DocumentFactory.LoadFromCache(cache, request.DocumentId))
            {
                DocumentHelper.CheckLoadFromCache(document);
                DocumentHelper.CheckPageNumber(document, pageNumber);

                var documentPage = document.Pages[pageNumber - 1];
                var image        = documentPage.GetSvgBackImage(rasterBackColor, request.Resolution);
                if (image != null)
                {
                    try
                    {
                        // Resize it (will only resize if both width and height are not 0), will also take care of FAX images (with different resolution)
                        ImageResizer.ResizeImage(image, request.Width, request.Height);
                        var stream = ImageSaver.SaveImage(image, document.RasterCodecs, saveFormat, request.MimeType, request.BitsPerPixel, request.QualityFactor);

                        // If we just return the stream, Web Api will try to serialize it.
                        // If the return type is "HttpResponseMessage" it will not serialize
                        // and you can set the content as you wish.
                        var response = new HttpResponseMessage();
                        response.Content = new StreamContent(stream);
                        ServiceHelper.UpdateCacheSettings(response);
                        return(response);
                    }
                    finally
                    {
                        image.Dispose();
                    }
                }
                else
                {
                    // Instead of throwing an exception, let's return the smallest possible GIF
                    //throw new ServiceException("No SVG Back Image exists", HttpStatusCode.NotFound);

                    var response = new HttpResponseMessage();
                    var data     = Convert.FromBase64String(PageController.smallest_GIF_base64);
                    var ms       = new MemoryStream(data);
                    response.Content = new StreamContent(ImageSaver.PrepareStream(ms, "image/gif"));
                    ServiceHelper.UpdateCacheSettings(response);
                    return(response);
                }
            }
        }