Beispiel #1
0
        /// <summary>
        /// Loads the expected image with a reference decoder + compares it to <paramref name="image"/>.
        /// Also performs a debug save using <see cref="ImagingTestCaseUtility.SaveTestOutputFile{TPixel}"/>.
        /// </summary>
        internal static void VerifyEncoder <TPixel>(
            this Image <TPixel> image,
            ITestImageProvider provider,
            string extension,
            object testOutputDetails,
            IImageEncoder encoder,
            ImageComparer customComparer   = null,
            bool appendPixelTypeToFileName = true,
            string referenceImageExtension = null,
            IImageDecoder referenceDecoder = null)
            where TPixel : struct, IPixel <TPixel>
        {
            string actualOutputFile = provider.Utility.SaveTestOutputFile(
                image,
                extension,
                encoder,
                testOutputDetails,
                appendPixelTypeToFileName);

            referenceDecoder = referenceDecoder ?? TestEnvironment.GetReferenceDecoder(actualOutputFile);

            using (var actualImage = Image.Load <TPixel>(actualOutputFile, referenceDecoder))
            {
                ImageComparer comparer = customComparer ?? ImageComparer.Exact;
                comparer.VerifySimilarity(actualImage, image);
            }
        }
 public static void DebugSave(
     this Image image,
     ITestImageProvider provider,
     IImageEncoder encoder,
     FormattableString testOutputDetails,
     bool appendPixelTypeToFileName = true)
 => image.DebugSave(provider, encoder, (object)testOutputDetails, appendPixelTypeToFileName);
Beispiel #3
0
        private static IImageEncoder GetEncoder(string extension)
        {
            IImageEncoder encoder = null;

            extension = extension.Replace(".", "");

            var isSupported = Regex.IsMatch(extension, "gif|png|jpe?g", RegexOptions.IgnoreCase);

            if (isSupported)
            {
                switch (extension.ToLower())
                {
                case "png":
                    encoder = new PngEncoder();
                    break;

                case "jpg":
                    encoder = new JpegEncoder();
                    break;

                case "jpeg":
                    encoder = new JpegEncoder();
                    break;

                case "gif":
                    encoder = new GifEncoder();
                    break;

                default:
                    break;
                }
            }

            return(encoder);
        }
Beispiel #4
0
        /// <summary>
        /// Writes the image to the given stream using the currently loaded image format.
        /// </summary>
        /// <param name="source">The source image.</param>
        /// <param name="filePath">The file path to save the image to.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the stream is null.</exception>
        public static void Save(this Image source, string filePath)
        {
            Guard.NotNullOrWhiteSpace(filePath, nameof(filePath));

            string       ext    = Path.GetExtension(filePath);
            IImageFormat format = source.GetConfiguration().ImageFormatsManager.FindFormatByFileExtension(ext);

            if (format is null)
            {
                var sb = new StringBuilder();
                sb.AppendLine($"No encoder was found for extension '{ext}'. Registered encoders include:");
                foreach (IImageFormat fmt in source.GetConfiguration().ImageFormats)
                {
                    sb.AppendLine($" - {fmt.Name} : {string.Join(", ", fmt.FileExtensions)}");
                }

                throw new NotSupportedException(sb.ToString());
            }

            IImageEncoder encoder = source.GetConfiguration().ImageFormatsManager.FindEncoder(format);

            if (encoder is null)
            {
                var sb = new StringBuilder();
                sb.AppendLine($"No encoder was found for extension '{ext}' using image format '{format.Name}'. Registered encoders include:");
                foreach (KeyValuePair <IImageFormat, IImageEncoder> enc in source.GetConfiguration().ImageFormatsManager.ImageEncoders)
                {
                    sb.AppendLine($" - {enc.Key} : {enc.Value.GetType().Name}");
                }

                throw new NotSupportedException(sb.ToString());
            }

            source.Save(filePath, encoder);
        }
        public string[] SaveTestOutputFileMultiFrame <TPixel>(
            Image <TPixel> image,
            string extension               = "png",
            IImageEncoder encoder          = null,
            object testOutputDetails       = null,
            bool appendPixelTypeToFileName = true)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            encoder ??= TestEnvironment.GetReferenceEncoder($"foo.{extension}");

            string[] files = this.GetTestOutputFileNamesMultiFrame(
                image.Frames.Count,
                extension,
                testOutputDetails,
                appendPixelTypeToFileName).ToArray();

            for (int i = 0; i < image.Frames.Count; i++)
            {
                using (Image <TPixel> frameImage = image.Frames.CloneFrame(i))
                {
                    string filePath = files[i];
                    using (FileStream stream = File.OpenWrite(filePath))
                    {
                        frameImage.Save(stream, encoder);
                    }
                }
            }

            return(files);
        }
Beispiel #6
0
 public static void Save(this Image image, string path, IImageEncoder encoder)
 {
     using (var stream = File.Create(path))
     {
         Save(image, stream, encoder);
     }
 }
        /// <summary>
        /// Writes the image to the given stream using the given image format.
        /// </summary>
        /// <param name="source">The source image.</param>
        /// <param name="stream">The stream to save the image to.</param>
        /// <param name="format">The format to save the image in.</param>
        /// <exception cref="ArgumentNullException">The stream is null.</exception>
        /// <exception cref="ArgumentNullException">The format is null.</exception>
        /// <exception cref="NotSupportedException">The stream is not writable.</exception>
        /// <exception cref="NotSupportedException">No encoder available for provided format.</exception>
        public static void Save(this Image source, Stream stream, IImageFormat format)
        {
            Guard.NotNull(stream, nameof(stream));
            Guard.NotNull(format, nameof(format));

            if (!stream.CanWrite)
            {
                throw new NotSupportedException("Cannot write to the stream.");
            }

            IImageEncoder encoder = source.GetConfiguration().ImageFormatsManager.FindEncoder(format);

            if (encoder is null)
            {
                var sb = new StringBuilder();
                sb.AppendLine("No encoder was found for the provided mime type. Registered encoders include:");

                foreach (KeyValuePair <IImageFormat, IImageEncoder> val in source.GetConfiguration().ImageFormatsManager.ImageEncoders)
                {
                    sb.AppendFormat(" - {0} : {1}{2}", val.Key.Name, val.Value.GetType().Name, Environment.NewLine);
                }

                throw new NotSupportedException(sb.ToString());
            }

            source.Save(stream, encoder);
        }
Beispiel #8
0
        private IPropagatorBlock <RenderedSceneTile <TPixel>, EncodedSceneTile> CreateImageEncoding <TPixel>(ZZMapsImageFormat format, ExecutionDataflowBlockOptions dataflowOptions, ProgressStep?progressStep)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            IImageEncoder encoder = format switch
            {
                ZZMapsImageFormat.Png => new PngEncoder()
                {
                    CompressionLevel = (PngCompressionLevel)Math.Clamp(options.PNGCompression,
                                                                       (int)PngCompressionLevel.BestSpeed, (int)PngCompressionLevel.BestCompression)
                },
                ZZMapsImageFormat.Jpeg => new JpegEncoder()
                {
                    Quality = Math.Clamp(options.JPEGQuality, 0, 100)
                },
                _ => throw new NotSupportedException($"Unsupported image format {format}")
            };

            return(new TransformBlock <RenderedSceneTile <TPixel>, EncodedSceneTile>(renderedTile =>
            {
                var stream = new MemoryStream();
                encoder.Encode(renderedTile.Image, stream);
                stream.Position = 0;
                progressStep?.Increment();
                return new EncodedSceneTile(renderedTile.SceneName, renderedTile.Layer, renderedTile.TileID, stream);
            }, dataflowOptions));
        }
Beispiel #9
0
        /// <summary>
        /// Saves the image to the given stream using the currently loaded image format.
        /// </summary>
        /// <param name="filePath">The file path to save the image to.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the stream is null.</exception>
        /// <returns>The <see cref="Image{TPixel}"/></returns>
        public Image <TPixel> Save(string filePath)
        {
            Guard.NotNullOrEmpty(filePath, nameof(filePath));

            string ext    = Path.GetExtension(filePath).Trim('.');
            var    format = this.Configuration.FindFormatByFileExtensions(ext);

            if (format == null)
            {
                var stringBuilder = new StringBuilder();
                stringBuilder.AppendLine($"Can't find a format that is associated with the file extention '{ext}'. Registered formats with there extensions include:");
                foreach (IImageFormat fmt in this.Configuration.ImageFormats)
                {
                    stringBuilder.AppendLine($" - {fmt.Name} : {string.Join(", ", fmt.FileExtensions)}");
                }

                throw new NotSupportedException(stringBuilder.ToString());
            }

            IImageEncoder encoder = this.Configuration.FindEncoder(format);

            if (encoder == null)
            {
                var stringBuilder = new StringBuilder();
                stringBuilder.AppendLine($"Can't find encoder for file extention '{ext}' using image format '{format.Name}'. Registered encoders include:");
                foreach (KeyValuePair <IImageFormat, IImageEncoder> enc in this.Configuration.ImageEncoders)
                {
                    stringBuilder.AppendLine($" - {enc.Key} : {enc.Value.GetType().Name}");
                }

                throw new NotSupportedException(stringBuilder.ToString());
            }

            return(this.Save(filePath, encoder));
        }
Beispiel #10
0
        public void ApplyEncoderDefaults(IImageEncoder encoder)
        {
            switch (encoder)
            {
            case BmpEncoder bmpEncoder:
                bmpEncoder.BitsPerPixel        = BmpBitsPerPixel.Pixel32;
                bmpEncoder.SupportTransparency = false;
                break;

            case GifEncoder:
                // Use the ImageSharp defaults
                break;

            case JpegEncoder jpegEncoder:
                jpegEncoder.ColorType = JpegColorType.Rgb;
                jpegEncoder.Quality   = 100;
                break;

            case PngEncoder pngEncoder:
                pngEncoder.BitDepth             = PngBitDepth.Bit16;
                pngEncoder.ColorType            = PngColorType.Rgb;
                pngEncoder.CompressionLevel     = PngCompressionLevel.NoCompression;
                pngEncoder.TransparentColorMode = PngTransparentColorMode.Clear;
                break;

            case TiffEncoder tiffEncoder:
                tiffEncoder.CompressionLevel = SixLabors.ImageSharp.Compression.Zlib.DeflateCompressionLevel.NoCompression;
                tiffEncoder.BitsPerPixel     = TiffBitsPerPixel.Bit24;
                break;

            default:
                throw new NotSupportedException("Unable to provide any default values for this encoder.");
            }
        }
Beispiel #11
0
        /// <summary>
        /// For a given file path find the best encoder to use via its extension.
        /// </summary>
        /// <param name="source">The source image.</param>
        /// <param name="filePath">The target file path to save the image to.</param>
        /// <returns>The matching encoder.</returns>
        public static IImageEncoder DetectEncoder(this Image source, string filePath)
        {
            Guard.NotNull(filePath, nameof(filePath));

            string       ext    = Path.GetExtension(filePath);
            IImageFormat format = source.GetConfiguration().ImageFormatsManager.FindFormatByFileExtension(ext);

            if (format is null)
            {
                var sb = new StringBuilder();
                sb.AppendLine($"No encoder was found for extension '{ext}'. Registered encoders include:");
                foreach (IImageFormat fmt in source.GetConfiguration().ImageFormats)
                {
                    sb.AppendFormat(" - {0} : {1}{2}", fmt.Name, string.Join(", ", fmt.FileExtensions), Environment.NewLine);
                }

                throw new NotSupportedException(sb.ToString());
            }

            IImageEncoder encoder = source.GetConfiguration().ImageFormatsManager.FindEncoder(format);

            if (encoder is null)
            {
                var sb = new StringBuilder();
                sb.AppendLine($"No encoder was found for extension '{ext}' using image format '{format.Name}'. Registered encoders include:");
                foreach (KeyValuePair <IImageFormat, IImageEncoder> enc in source.GetConfiguration().ImageFormatsManager.ImageEncoders)
                {
                    sb.AppendFormat(" - {0} : {1}{2}", enc.Key, enc.Value.GetType().Name, Environment.NewLine);
                }

                throw new NotSupportedException(sb.ToString());
            }

            return(encoder);
        }
        private static Configuration CreateDefaultConfiguration()
        {
            var cfg = new Configuration(
                new JpegConfigurationModule(),
                new GifConfigurationModule()
                );

            // Magick codecs should work on all platforms
            IImageEncoder pngEncoder = IsWindows ? (IImageEncoder)SystemDrawingReferenceEncoder.Png : new PngEncoder();
            IImageEncoder bmpEncoder = IsWindows ? (IImageEncoder)SystemDrawingReferenceEncoder.Bmp : new BmpEncoder();

            cfg.ConfigureCodecs(
                ImageFormats.Png,
                MagickReferenceDecoder.Instance,
                pngEncoder,
                new PngImageFormatDetector());

            cfg.ConfigureCodecs(
                ImageFormats.Bmp,
                SystemDrawingReferenceDecoder.Instance,
                bmpEncoder,
                new BmpImageFormatDetector());

            return(cfg);
        }
Beispiel #13
0
        public ImageRenderer(
            int pixelSize                = 10,
            int barHeightFor1DBarcode    = 40,
            ImageFormat imageFormat      = ImageFormat.Png,
            int jpegQuality              = 75,
            bool includeEanContentAsText = false,
            string eanFontFamily         = null)
        {
            if (pixelSize <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(pixelSize), "Value must be larger than zero");
            }
            if (barHeightFor1DBarcode <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(barHeightFor1DBarcode), "Value must be larger than zero");
            }
            if (jpegQuality < 0 || jpegQuality > 100)
            {
                throw new ArgumentOutOfRangeException(nameof(jpegQuality), "Value must be a value between 0 and 100");
            }

            _pixelSize               = pixelSize;
            _barHeightFor1DBarcode   = barHeightFor1DBarcode;
            _imageEncoder            = GetImageEncoder(imageFormat, jpegQuality);
            _includeEanContentAsText = includeEanContentAsText;
            _eanFontFamily           = eanFontFamily ?? "Arial";
        }
Beispiel #14
0
        /// <summary>
        /// Encode the image into a byte array in accordance with the specified image format
        /// </summary>
        /// <typeparam name="T">Pixel data type</typeparam>
        /// <param name="image">Image data</param>
        /// <param name="imageFormat">Image format</param>
        /// <param name="quality">Quality index that will be used to encode the image</param>
        /// <returns>Image binary data</returns>
        protected virtual byte[] EncodeImage <T>(Image <T> image, IImageFormat imageFormat, int?quality = null) where T : struct, IPixel <T>
        {
            using (MemoryStream stream = new MemoryStream())
            {
                IImageEncoder imageEncoder = SixLabors.ImageSharp.Configuration.Default.ImageFormatsManager.FindEncoder(imageFormat);
                switch (imageEncoder)
                {
                case JpegEncoder jpegEncoder:
                    jpegEncoder.Quality = quality ?? _mediaSettings.DefaultImageQuality;
                    jpegEncoder.Encode(image, stream);
                    break;

                case PngEncoder pngEncoder:
                    pngEncoder.ColorType = PngColorType.Rgb;
                    pngEncoder.Encode(image, stream);
                    break;

                case BmpEncoder bmpEncoder:
                    bmpEncoder.BitsPerPixel = BmpBitsPerPixel.Pixel32;
                    bmpEncoder.Encode(image, stream);
                    break;

                case GifEncoder gifEncoder:
                    gifEncoder.Encode(image, stream);
                    break;

                default:
                    imageEncoder.Encode(image, stream);
                    break;
                }

                return(stream.ToArray());
            }
        }
Beispiel #15
0
        private Size GetOptimumImageSize(Image image, int maxFileSize, IImageEncoder imageEncoder)
        {
            Size size             = image.Size();
            int  maxPossibleWidth = size.Width;
            int  minPossibleWidth = GetMinimumPossibleWidth(size, maxFileSize);

            long imageFileSize = 0;
            long lastImageFileSize;
            Size trySize = size;

            // use binary search to find maximum size within filesize constraint
            do
            {
                lastImageFileSize = imageFileSize;
                imageFileSize     = GetImageFileSize(image, trySize, imageEncoder);

                if (imageFileSize > maxFileSize)
                {
                    maxPossibleWidth = trySize.Width - 1;
                }
                else
                {
                    minPossibleWidth = trySize.Width;
                }

                int tryWidth  = (minPossibleWidth + maxPossibleWidth) / 2;
                int tryHeight = (tryWidth * size.Height) / size.Width;
                trySize = new Size(tryWidth, tryHeight);
            } while (maxPossibleWidth > (minPossibleWidth + 1));

            return(new Size(minPossibleWidth, (minPossibleWidth * size.Height) / size.Width));
        }
Beispiel #16
0
 /// <summary>
 /// Sets a specific image encoder as the encoder for a specific image format.
 /// </summary>
 /// <param name="imageFormat">The image format to register the encoder for.</param>
 /// <param name="encoder">The encoder to use,</param>
 public void SetEncoder(IImageFormat imageFormat, IImageEncoder encoder)
 {
     Guard.NotNull(imageFormat, nameof(imageFormat));
     Guard.NotNull(encoder, nameof(encoder));
     this.AddImageFormat(imageFormat);
     this.mimeTypeEncoders.AddOrUpdate(imageFormat, encoder, (s, e) => encoder);
 }
Beispiel #17
0
        public static async void LimitImageScale(string path, int maxWidth, int maxHeight)
        {
            await Task.Run(() =>
            {
                try
                {
                    IImageFormat format   = Image.DetectFormat(path);
                    IImageEncoder encoder = null;
                    if (format == Png)
                    {
                        encoder = PngEncoder;
                    }
                    else if (format == Jpeg)
                    {
                        encoder = JpegEncoder;
                    }
                    else if (format == Bmp)
                    {
                        encoder = BmpEncoder;
                    }
                    else if (format == Gif)
                    {
                        encoder = GifEncoder;
                    }
                    else
                    {
                        return;
                    }

                    var image  = Image.Load <Rgba32>(path);
                    bool flag  = false;
                    var width  = image.Width;
                    var height = image.Height;
                    if (width > maxWidth)
                    {
                        flag     = true;
                        var rate = (double)maxWidth / width;
                        width    = Convert.ToInt32(Math.Floor(width *rate));
                        height   = Convert.ToInt32(Math.Floor(height *rate));
                    }
                    if (height > maxHeight)
                    {
                        flag     = true;
                        var rate = (double)maxHeight / height;
                        width    = Convert.ToInt32(Math.Floor(width *rate));
                        height   = Convert.ToInt32(Math.Floor(height *rate));
                    }
                    if (flag)
                    {
                        image.Mutate(x => x.Resize(width, height, new BoxResampler()));
                        image.Save(path, encoder);
                    }
                }
                catch (Exception ex)
                {
                    ConsoleLog.Error("Image Utils", ex.GetFormatString());
                }
            });
        }
 public ContourTracingDetector(
     IImageEncoder imageEncoder,
     IBlobSearcher blobSearcher
     )
 {
     m_imageEncoder = imageEncoder;
     m_blobSearcher = blobSearcher;
 }
Beispiel #19
0
        /// <summary>
        /// Saves the image to the given stream using the given image encoder.
        /// </summary>
        /// <param name="stream">The stream to save the image to.</param>
        /// <param name="encoder">The encoder to save the image with.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
        /// <exception cref="ArgumentNullException">Thrown if the stream or encoder is null.</exception>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public Task SaveAsync(Stream stream, IImageEncoder encoder, CancellationToken cancellationToken = default)
        {
            Guard.NotNull(stream, nameof(stream));
            Guard.NotNull(encoder, nameof(encoder));
            this.EnsureNotDisposed();

            return(this.AcceptVisitorAsync(new EncodeVisitor(encoder, stream), cancellationToken));
        }
 public RecursiveBasedDetector(
     IImageEncoder imageEncoder,
     IBlobSearcher blobSearcher
     )
 {
     m_imageEncoder = imageEncoder;
     m_blobSearcher = blobSearcher;
 }
Beispiel #21
0
 public static byte[] ToBytes(this Image <Rgba32> image, IImageEncoder encoder = null)
 {
     using (var m = new MemoryStream())
     {
         image.Save(m, _encoder);
         return(m.ToArray());
     }
 }
Beispiel #22
0
 public static byte[] ToByteArray(this Image <Rgba32> imageIn, IImageEncoder encoder)
 {
     using (var ms = new MemoryStream())
     {
         imageIn.Save(ms, encoder);
         return(ms.ToArray());
     }
 }
Beispiel #23
0
 public static byte[] ToArray <TPixel>(this Image <TPixel> image, IImageEncoder encoder) where TPixel : unmanaged, IPixel <TPixel>
 {
     using (var memoryStream = new MemoryStream())
     {
         image.Save(memoryStream, encoder);
         return(memoryStream.ToArray());
     }
 }
Beispiel #24
0
 /// <summary>
 /// Writes the image to the given stream using the currently loaded image format.
 /// </summary>
 /// <param name="source">The source image.</param>
 /// <param name="filePath">The file path to save the image to.</param>
 /// <param name="encoder">The encoder to save the image with.</param>
 /// <exception cref="ArgumentNullException">Thrown if the encoder is null.</exception>
 public static void Save(this Image source, string filePath, IImageEncoder encoder)
 {
     Guard.NotNull(encoder, nameof(encoder));
     using (Stream fs = source.GetConfiguration().FileSystem.Create(filePath))
     {
         source.Save(fs, encoder);
     }
 }
Beispiel #25
0
 public void Save(Stream stream, IImageEncoder encoder)
 {
     if (stream == null)
     {
         throw new ArgumentNullException();
     }
     encoder.Encode(this, stream);
 }
Beispiel #26
0
 /// <summary>
 /// Saves the image to the given stream using the currently loaded image format.
 /// </summary>
 /// <param name="filePath">The file path to save the image to.</param>
 /// <param name="encoder">The encoder to save the image with.</param>
 /// <param name="options">The options for the encoder.</param>
 /// <exception cref="System.ArgumentNullException">Thrown if the encoder is null.</exception>
 /// <returns>The <see cref="Image{TColor}"/></returns>
 public Image <TColor> Save(string filePath, IImageEncoder encoder, IEncoderOptions options)
 {
     Guard.NotNull(encoder, nameof(encoder));
     using (FileStream fs = File.Create(filePath))
     {
         return(this.Save(fs, encoder));
     }
 }
Beispiel #27
0
        /// <summary>
        /// Saves the image to the given stream using the given image encoder.
        /// </summary>
        /// <param name="stream">The stream to save the image to.</param>
        /// <param name="encoder">The encoder to save the image with.</param>
        /// <exception cref="ArgumentNullException">Thrown if the stream or encoder is null.</exception>
        public void Save(Stream stream, IImageEncoder encoder)
        {
            Guard.NotNull(stream, nameof(stream));
            Guard.NotNull(encoder, nameof(encoder));
            this.EnsureNotDisposed();

            this.AcceptVisitor(new EncodeVisitor(encoder, stream));
        }
Beispiel #28
0
        /// <summary>
        /// Saves the image to the given stream using the given image encoder.
        /// </summary>
        /// <param name="stream">The stream to save the image to.</param>
        /// <param name="encoder">The encoder to save the image with.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the stream or encoder is null.</exception>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task SaveAsync(Stream stream, IImageEncoder encoder)
        {
            Guard.NotNull(stream, nameof(stream));
            Guard.NotNull(encoder, nameof(encoder));
            this.EnsureNotDisposed();

            await this.AcceptVisitorAsync(new EncodeVisitor(encoder, stream)).ConfigureAwait(false);
        }
Beispiel #29
0
 /// <summary>
 /// Saves the image to the given stream using the currently loaded image format.
 /// </summary>
 /// <param name="filePath">The file path to save the image to.</param>
 /// <param name="encoder">The encoder to save the image with.</param>
 /// <param name="options">The options for the encoder.</param>
 /// <exception cref="System.ArgumentNullException">Thrown if the encoder is null.</exception>
 /// <returns>The <see cref="Image{TPixel}"/></returns>
 public Image <TPixel> Save(string filePath, IImageEncoder encoder, IEncoderOptions options)
 {
     Guard.NotNull(encoder, nameof(encoder));
     using (Stream fs = this.Configuration.FileSystem.Create(filePath))
     {
         return(this.Save(fs, encoder, options));
     }
 }
Beispiel #30
0
 void SaveToImage(Canvas canvas, SaveFileDialog dialog, IImageEncoder encoder)
 {
     using (var stream = dialog.OpenFile())
     {
         var image = canvas.ToImage();
         encoder.Encode(image, stream);
     }
 }
        public VideoStreamingService(ICameraController cameraController, IImageEncoder imageEncoder,
            IModuleConfiguration moduleConfiguration, IWebClient webClient)
        {
            encoder = imageEncoder;
            SendImage += OnSendImage;

            client = webClient;
            controller = cameraController;
            configuration = moduleConfiguration;

            configuration.StreamingValueChanged += OnStreamingValueChanged;
            configuration.CurrentVideoSizeChanged += OnCurrentVideoSizeChanged;
        }
Beispiel #32
0
        public ImageProcessor(ILogger logger,
            IServerApplicationPaths appPaths,
            IFileSystem fileSystem,
            IJsonSerializer jsonSerializer,
            IImageEncoder imageEncoder,
            int maxConcurrentImageProcesses, Func<ILibraryManager> libraryManager)
        {
            _logger = logger;
            _fileSystem = fileSystem;
            _jsonSerializer = jsonSerializer;
            _imageEncoder = imageEncoder;
            _libraryManager = libraryManager;
            _appPaths = appPaths;

            ImageEnhancers = new List<IImageEnhancer>();
            _saveImageSizeTimer = new Timer(SaveImageSizeCallback, null, Timeout.Infinite, Timeout.Infinite);

            Dictionary<Guid, ImageSize> sizeDictionary;

            try
            {
                sizeDictionary = jsonSerializer.DeserializeFromFile<Dictionary<Guid, ImageSize>>(ImageSizeFile) ??
                    new Dictionary<Guid, ImageSize>();
            }
            catch (FileNotFoundException)
            {
                // No biggie
                sizeDictionary = new Dictionary<Guid, ImageSize>();
            }
            catch (DirectoryNotFoundException)
            {
                // No biggie
                sizeDictionary = new Dictionary<Guid, ImageSize>();
            }
            catch (Exception ex)
            {
                logger.ErrorException("Error parsing image size cache file", ex);

                sizeDictionary = new Dictionary<Guid, ImageSize>();
            }

            _cachedImagedSizes = new ConcurrentDictionary<Guid, ImageSize>(sizeDictionary);
            _logger.Info("ImageProcessor started with {0} max concurrent image processes", maxConcurrentImageProcesses);
            _imageProcessingSemaphore = new SemaphoreSlim(maxConcurrentImageProcesses, maxConcurrentImageProcesses);
        }
 public static void Save(this Image image, string path, IImageEncoder encoder)
 {
     using (var stream = File.Create(path))
     {
         Save(image, stream, encoder);
     }
 }
 public ClipboardService(IClipboard clipboard, IImageEncoder encoder, IMimeTypeResolver mimeTypeResolver)
 {
     _clipboard = clipboard;
     _encoder = encoder;
     _mimeTypeResolver = mimeTypeResolver;
 }
 public static void Save(this Image image, Stream stream, IImageEncoder encoder) => encoder.Encode(image, stream);
Beispiel #36
0
 void SaveToImage(Canvas canvas, SaveFileDialog dialog, IImageEncoder encoder)
 {
     using (var stream = dialog.OpenFile())
     {
         var image = canvas.ToImage();
         encoder.Encode(image, stream);
     }
 }
Beispiel #37
0
        //Handles encoding/decoding using the correct method and settings when the 'Proceed' button is pressed.
        private void _encodeOrDecodeImage() {
            if (rdioEncode.Checked) {
                if (picResult.Image != null) {
                    picResult.Image.Dispose();
                }

                byte[] msg = _getMessageFromTextboxOrFile();

                //Create an _imageEncoder according according to selected method
                if (!OptionsForm.LSBMethodSelected) {
                    lblProcessing.Text = "Encoding using GT method...";
                    lblProcessing.Visible = true;
                    Application.DoEvents();

                    //Use simple constructor if a table is null 
                    if (OptionsForm.QuantizationTableY == null || OptionsForm.QuantizationTableChr == null || OptionsForm.HuffmanTableYAC == null || OptionsForm.HuffmanTableYDC == null || OptionsForm.HuffmanTableChrAC == null || OptionsForm.HuffmanTableChrDC == null) {
                        _imageEncoder = new JpegImage(CoverImage, OptionsForm.Quality, OptionsForm.MValue);
                    } else {
                        _imageEncoder = new JpegImage(CoverImage, OptionsForm.Quality, OptionsForm.MValue, OptionsForm.QuantizationTableY, OptionsForm.QuantizationTableChr, OptionsForm.HuffmanTableYDC, OptionsForm.HuffmanTableYAC, OptionsForm.HuffmanTableChrDC, OptionsForm.HuffmanTableChrAC);
                    }
                } else {
                    lblProcessing.Text = "Encoding using LSB method...";
                    lblProcessing.Visible = true;
                    Application.DoEvents();
                    _imageEncoder = new LeastSignificantBitImage(CoverImage);
                }

                //Encode
                try {
                    _imageEncoder.Encode(msg);
                    _imageEncoder.Save(_userSavePath);
                    picResult.Image = Image.FromFile(_userSavePath);
                }
                catch (ImageCannotContainDataException) {
                    MessageBox.Show("Image cannot contain data!");
                }
                catch (ExternalException) {
                    MessageBox.Show("Failed to load result picture! Your Huffman table may be invalid");
                }
                catch (Exception) {
                    MessageBox.Show("An error occured when encoding!");
                }
            } else if (rdioDecode.Checked) {
                picResult.Image = null;
                tbMessage.Text = "";

                if (!OptionsForm.LSBMethodSelected) {
                    lblProcessing.Text = "Decoding using GT method...";
                    lblProcessing.Visible = true;
                    Application.DoEvents();
                    _imageDecoder = new JPEGDecoder(_decodeFilePath);
                } else {
                    lblProcessing.Text = "Decoding using LSB method...";
                    lblProcessing.Visible = true;
                    Application.DoEvents();
                    _imageDecoder = new LeastSignificantBitDecoder(_decodeFilePath);
                }

                //Decode
                try {
                    byte[] message = _imageDecoder.Decode();
                    tbMessage.Text = new string(message.Select(x => (char)x).ToArray());
                    File.WriteAllBytes(_userSavePath, message);
                }
                catch (Exception) {
                    MessageBox.Show("An Error occured when decoding! Cover image might not contain a message.");
                }
            }
        }