Example #1
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));
        }
Example #2
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());
            }
        }
Example #3
0
 public void Save(Stream stream, IImageEncoder encoder)
 {
     if (stream == null)
     {
         throw new ArgumentNullException();
     }
     encoder.Encode(this, stream);
 }
Example #4
0
 void SaveToImage(Canvas canvas, SaveFileDialog dialog, IImageEncoder encoder)
 {
     using (var stream = dialog.OpenFile())
     {
         var image = canvas.ToImage();
         encoder.Encode(image, stream);
     }
 }
Example #5
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="options">The options for the encoder.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the stream or encoder is null.</exception>
        /// <returns>
        /// The <see cref="Image{TPixel}"/>.
        /// </returns>
        public Image <TPixel> Save(Stream stream, IImageEncoder encoder, IEncoderOptions options)
        {
            Guard.NotNull(stream, nameof(stream));
            Guard.NotNull(encoder, nameof(encoder));

            encoder.Encode(this, stream, options);

            return(this);
        }
Example #6
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 is null.</exception>
        /// <returns>
        /// The <see cref="Image{TColor}"/>.
        /// </returns>
        public Image <TColor> Save(Stream stream, IImageEncoder encoder)
        {
            Guard.NotNull(stream, nameof(stream));
            encoder.Encode(this, stream);

            // Reset to the start of the stream.
            if (stream.CanSeek)
            {
                stream.Position = 0;
            }

            return(this);
        }
Example #7
0
    static byte[] Write(IImageEncoder encoder, uint[] palette, IReadOnlyTexture <byte> existing, int frameNum)
    {
        var frame  = existing.Regions[frameNum];
        var buffer = new ReadOnlyImageBuffer <byte>(
            frame.Width,
            frame.Height,
            existing.Width,
            existing.PixelData.Slice(frame.PixelOffset, frame.PixelLength));

        Image <Rgba32> image = ImageSharpUtil.ToImageSharp(buffer, palette);
        var            bytes = FormatUtil.BytesFromStream(stream => encoder.Encode(image, stream));

        return(bytes);
    }
Example #8
0
        public static void Save(
            this IEnumerable <IReadOnlyPixelRows> images,
            IImagingConfig imagingConfig,
            Stream output,
            ImageFormat format,
            EncoderOptions?encoderOptions = null,
            ImagingProgressCallback <IImageEncoder>?onProgress = null,
            CancellationToken cancellationToken = default)
        {
            if (images == null)
            {
                throw new ArgumentNullException(nameof(images));
            }
            if (imagingConfig == null)
            {
                throw new ArgumentNullException(nameof(imagingConfig));
            }
            if (format == null)
            {
                throw new ArgumentNullException(nameof(format));
            }
            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            if (!output.CanWrite)
            {
                throw new ArgumentException("The stream is not writable.", nameof(output));
            }

            using IImageEncoder encoder = imagingConfig.CreateEncoder(output, format, encoderOptions);

            if (onProgress != null && encoder is IProgressReportingCoder <IImageEncoder> progressReporter)
            {
                progressReporter.Progress += onProgress;
            }

            foreach (IReadOnlyPixelRows image in images)
            {
                if (!encoder.CanEncodeImage(image))
                {
                    break;
                }

                encoder.Encode(image, cancellationToken);
            }
        }
Example #9
0
        /// <summary>
        /// This method pre-seeds the decoder and encoder for a given pixel format in the AoT compiler for iOS.
        /// </summary>
        /// <param name="decoder">The image decoder to seed.</param>
        /// <param name="encoder">The image encoder to seed.</param>
        /// <typeparam name="TPixel">The pixel format.</typeparam>
        private static void AotCodec <TPixel>(IImageDecoder decoder, IImageEncoder encoder)
            where TPixel : struct, IPixel <TPixel>
        {
            try
            {
                decoder.Decode <TPixel>(Configuration.Default, null);
            }
            catch
            {
            }

            try
            {
                encoder.Encode <TPixel>(null, null);
            }
            catch
            {
            }
        }
        public static void Save(this IImage image, Stream stream, IFileFormat imageFormat, IImageEncoderOptions encoderOptions)
        {
            IImageEncoder encoder = ImageCodec.FromFileFormat(imageFormat);

            if (encoder is null)
            {
                throw new UnsupportedFileFormatException();
            }

            encoder.Encode(image, stream, encoderOptions);

            if (stream.CanSeek && encoderOptions.OptimizationMode != ImageOptimizationMode.None)
            {
                IImageOptimizer imageOptimizer = ImageOptimizer.FromImageFormat(imageFormat);

                if (!(imageOptimizer is null))
                {
                    stream.Seek(0, SeekOrigin.Begin);

                    imageOptimizer.Optimize(stream, encoderOptions.OptimizationMode);
                }
            }
        }
Example #11
0
        /// <summary>
        /// Writes to specified image to the stream. The method loops through all encoders and
        /// uses the encoder which supports the extension of the specified file name.
        /// </summary>
        /// <param name="image">The image to write to the stream. Cannot be null.</param>
        /// <param name="stream">The target stream. Cannot be null.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <exception cref="ArgumentNullException">
        ///     <para><paramref name="image"/> is null (Nothing in Visual Basic).</para>
        ///     <para>- or -</para>
        ///     <para><paramref name="stream"/> is null (Nothing in Visual Basic).</para>
        /// </exception>
        public static void WriteToStream(this ExtendedImage image, Stream stream, string fileName)
        {
            Contract.Requires <ArgumentNullException>(image != null, "Image cannot be null.");
            Contract.Requires <ArgumentException>(image.IsFilled, "Image has not been loaded.");
            Contract.Requires <ArgumentNullException>(stream != null, "Stream cannot be null.");
            Contract.Requires <ArgumentException>(!string.IsNullOrEmpty(fileName), "File name cannot be null or empty.");

            string path = Path.GetExtension(fileName);

            if (path == null || string.IsNullOrEmpty(path))
            {
                throw new ArgumentException("The file name is not valid and contains no extension.");
            }

            string pathExtension = path.Substring(1);

            Contract.Assume(!string.IsNullOrEmpty(pathExtension));

            IImageEncoder encoder = null;

            foreach (IImageEncoder availableEncoder in Encoders.GetAvailableEncoders())
            {
                if (availableEncoder != null && availableEncoder.IsSupportedFileExtension(pathExtension))
                {
                    encoder = availableEncoder;
                    break;
                }
            }

            if (encoder == null)
            {
                throw new UnsupportedImageFormatException("Specified file extension is not supported.");
            }

            encoder.Encode(image, stream);
        }
        /// <summary>
        /// Converts the image to a stream, which can be assigned to
        /// a silverlight image control as image source and applies the specified
        /// filter before converting the image. The encoder to use will be created by
        /// the file extension name.
        /// </summary>
        /// <param name="image">The image, which should be converted. Cannot be null
        /// (Nothing in Visual Basic).</param>
        /// <param name="extension">The file extension to create the <see cref="IImageEncoder"/> that
        /// will be used to create an image stream.</param>
        /// <returns>The resulting stream.</returns>
        /// <exception cref="ArgumentException"><paramref name="extension"/> is empty or
        /// contains only blanks.</exception>
        /// <exception cref="ArgumentNullException">
        ///     <para><paramref name="image"/> is null (Nothing in Visual Basic).</para>
        ///     <para>- or -</para>
        ///     <para><paramref name="extension"/> is null (Nothing in Visual Basic).</para>
        /// </exception>
        public static Stream ToStreamByExtension(this ExtendedImage image, string extension)
        {
            Contract.Requires <ArgumentNullException>(image != null, "Image cannot be null.");
            Contract.Requires <ArgumentException>(image.IsFilled, "Image has not been loaded.");
            Contract.Requires <ArgumentException>(!string.IsNullOrEmpty(extension), "Extension cannot be null or empty.");

            IImageEncoder encoder = null;

            foreach (IImageEncoder availableEncoder in Encoders.GetAvailableEncoders())
            {
                if (availableEncoder != null && availableEncoder.IsSupportedFileExtension(extension))
                {
                    encoder = availableEncoder;
                    break;
                }
            }

            MemoryStream memoryStream = null;

            try
            {
                memoryStream = new MemoryStream();
                encoder.Encode(image, memoryStream);

                memoryStream.Seek(0, SeekOrigin.Begin);
            }
            catch
            {
                if (memoryStream != null)
                {
                    memoryStream.Dispose();
                }
                throw;
            }
            return(memoryStream);
        }
Example #13
0
        static byte[] Write(IImageEncoder encoder, uint[] palette, IReadOnlyTexture <byte> existing)
        {
            var image = ImageSharpUtil.PackSpriteSheet(palette, existing.Regions.Count, existing.GetRegionBuffer);

            return(FormatUtil.BytesFromStream(stream => encoder.Encode(image, stream)));
        }
Example #14
0
 public static void Save(this Image image, Stream stream, IImageEncoder encoder) => encoder.Encode(image, stream);
Example #15
0
 void SaveToImage(Canvas canvas, SaveFileDialog dialog, IImageEncoder encoder)
 {
     using (var stream = dialog.OpenFile())
     {
         var image = canvas.ToImage();
         encoder.Encode(image, stream);
     }
 }
 public static void Save(this Image image, Stream stream, IImageEncoder encoder) => encoder.Encode(image, stream);
Example #17
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 is null.</exception>
 public Image <T, TP> Save(Stream stream, IImageEncoder encoder)
 {
     Guard.NotNull(stream, nameof(stream));
     encoder.Encode(this, stream);
     return(this);
 }