QuickImage – Rev 1

Subversion Repositories:
Rev:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using ImageMagick;
using ImageMagick.Formats;
using Serilog;

namespace QuickImage
{
    public class ImageTool
    {
        private readonly MagickReadSettings _magickReaderSettings;

        public ImageTool()
        {
            _magickReaderSettings = new MagickReadSettings { FrameIndex = 0, FrameCount = 1 };
        }

        /// <summary>
        /// Convert an image to a given image format.
        /// </summary>
        /// <param name="fileName">the source file name to convert</param>
        /// <param name="format">the format to convert to</param>
        /// <param name="cancellationToken">a cancellation token</param>
        /// <returns>a stream containing image bytes iff. successful</returns>
        public async Task<Stream> ConvertTo(string fileName, MagickFormat format, CancellationToken cancellationToken)
        {
            try
            {
                using var imageCollection = new MagickImageCollection(fileName);
                var memoryStream = new MemoryStream();
                await imageCollection.WriteAsync(memoryStream, format, cancellationToken);
                imageCollection.Dispose();
                memoryStream.Position = 0L;
                return memoryStream;
            }
            catch
            {
                return Stream.Null;
            }
        }

        /// <summary>
        /// Convert an image to a given image format.
        /// </summary>
        /// <param name="fileStream">the source stream to convert</param>
        /// <param name="format">the format to convert to</param>
        /// <param name="cancellationToken">a cancellation token</param>
        /// <returns>a stream containing image bytes iff. successful</returns>
        public async Task<Stream> ConvertTo(Stream fileStream, MagickFormat format, CancellationToken cancellationToken)
        {
            try
            {
                using var imageCollection = new MagickImageCollection(fileStream);
                var memoryStream = new MemoryStream();
                await imageCollection.WriteAsync(memoryStream, format, cancellationToken);
                imageCollection.Dispose();
                memoryStream.Position = 0L;
                return memoryStream;
            }
            catch
            {
                return Stream.Null;
            }
        }
    }
}