Beispiel #1
0
        public async Task <string> ProcessImage(ImageProcessingOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            var originalImagePath = options.Image.Path;

            if (options.HasDefaultOptions(originalImagePath) && options.Enhancers.Count == 0 && !options.CropWhiteSpace)
            {
                // Just spit out the original file if all the options are default
                return(originalImagePath);
            }

            var dateModified = options.Image.DateModified;

            if (options.CropWhiteSpace)
            {
                var tuple = await GetWhitespaceCroppedImage(originalImagePath, dateModified).ConfigureAwait(false);

                originalImagePath = tuple.Item1;
                dateModified      = tuple.Item2;
            }

            if (options.Enhancers.Count > 0)
            {
                var tuple = await GetEnhancedImage(options.Image, options.Item, options.ImageIndex, options.Enhancers).ConfigureAwait(false);

                originalImagePath = tuple.Item1;
                dateModified      = tuple.Item2;
            }

            var originalImageSize = GetImageSize(originalImagePath, dateModified);

            // Determine the output size based on incoming parameters
            var newSize = DrawingUtils.Resize(originalImageSize, options.Width, options.Height, options.MaxWidth, options.MaxHeight);

            if (options.HasDefaultOptionsWithoutSize(originalImagePath) && newSize.Equals(originalImageSize) && options.Enhancers.Count == 0)
            {
                // Just spit out the original file if the new size equals the old
                return(originalImagePath);
            }

            var quality = options.Quality ?? 90;

            var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, options.OutputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.BackgroundColor);

            var semaphore = GetLock(cacheFilePath);

            await semaphore.WaitAsync().ConfigureAwait(false);

            // Check again in case of lock contention
            try
            {
                if (File.Exists(cacheFilePath))
                {
                    semaphore.Release();
                    return(cacheFilePath);
                }
            }
            catch
            {
                semaphore.Release();
                throw;
            }

            try
            {
                var hasPostProcessing = !string.IsNullOrEmpty(options.BackgroundColor) || options.UnplayedCount.HasValue || options.AddPlayedIndicator || options.PercentPlayed > 0;

                using (var fileStream = _fileSystem.GetFileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
                {
                    // Copy to memory stream to avoid Image locking file
                    using (var memoryStream = new MemoryStream())
                    {
                        await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);

                        using (var originalImage = Image.FromStream(memoryStream, true, false))
                        {
                            var newWidth  = Convert.ToInt32(newSize.Width);
                            var newHeight = Convert.ToInt32(newSize.Height);

                            // Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here
                            // Also, Webp only supports Format32bppArgb and Format32bppRgb
                            var pixelFormat = options.OutputFormat == ImageOutputFormat.Webp
                                ? PixelFormat.Format32bppArgb
                                : PixelFormat.Format32bppPArgb;

                            using (var thumbnail = new Bitmap(newWidth, newHeight, pixelFormat))
                            {
                                // Mono throw an exeception if assign 0 to SetResolution
                                if (originalImage.HorizontalResolution > 0 && originalImage.VerticalResolution > 0)
                                {
                                    // Preserve the original resolution
                                    thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
                                }

                                using (var thumbnailGraph = Graphics.FromImage(thumbnail))
                                {
                                    thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
                                    thumbnailGraph.SmoothingMode      = SmoothingMode.HighQuality;
                                    thumbnailGraph.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                                    thumbnailGraph.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                                    thumbnailGraph.CompositingMode    = !hasPostProcessing ?
                                                                        CompositingMode.SourceCopy :
                                                                        CompositingMode.SourceOver;

                                    SetBackgroundColor(thumbnailGraph, options);

                                    thumbnailGraph.DrawImage(originalImage, 0, 0, newWidth, newHeight);

                                    DrawIndicator(thumbnailGraph, newWidth, newHeight, options);

                                    var outputFormat = GetOutputFormat(originalImage, options.OutputFormat);

                                    Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));

                                    // Save to the cache location
                                    using (var cacheFileStream = _fileSystem.GetFileStream(cacheFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, false))
                                    {
                                        if (options.OutputFormat == ImageOutputFormat.Webp)
                                        {
                                            new SimpleEncoder().Encode(thumbnail, cacheFileStream, quality, false);
                                        }
                                        else
                                        {
                                            // Save to the memory stream
                                            thumbnail.Save(outputFormat, cacheFileStream, quality);
                                        }
                                    }

                                    return(cacheFilePath);
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                semaphore.Release();
            }
        }
Beispiel #2
0
        public async Task <string> ProcessImage(ImageProcessingOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            var originalImagePath = options.Image.Path;

            if (options.HasDefaultOptions(originalImagePath) && options.Enhancers.Count == 0 && !options.CropWhiteSpace)
            {
                // Just spit out the original file if all the options are default
                return(originalImagePath);
            }

            var dateModified = options.Image.DateModified;

            if (options.CropWhiteSpace)
            {
                var tuple = await GetWhitespaceCroppedImage(originalImagePath, dateModified).ConfigureAwait(false);

                originalImagePath = tuple.Item1;
                dateModified      = tuple.Item2;
            }

            if (options.Enhancers.Count > 0)
            {
                var tuple = await GetEnhancedImage(options.Image, options.Item, options.ImageIndex, options.Enhancers).ConfigureAwait(false);

                originalImagePath = tuple.Item1;
                dateModified      = tuple.Item2;
            }

            var originalImageSize = GetImageSize(originalImagePath, dateModified);

            // Determine the output size based on incoming parameters
            var newSize = DrawingUtils.Resize(originalImageSize, options.Width, options.Height, options.MaxWidth, options.MaxHeight);

            if (options.HasDefaultOptionsWithoutSize(originalImagePath) && newSize.Equals(originalImageSize) && options.Enhancers.Count == 0)
            {
                // Just spit out the original file if the new size equals the old
                return(originalImagePath);
            }

            var quality = options.Quality ?? 90;

            var outputFormat  = GetOutputFormat(options.OutputFormat);
            var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.BackgroundColor);

            var semaphore = GetLock(cacheFilePath);

            await semaphore.WaitAsync().ConfigureAwait(false);

            // Check again in case of lock contention
            try
            {
                if (File.Exists(cacheFilePath))
                {
                    semaphore.Release();
                    return(cacheFilePath);
                }
            }
            catch
            {
                semaphore.Release();
                throw;
            }

            try
            {
                CheckDisposed();

                var newWidth  = Convert.ToInt32(newSize.Width);
                var newHeight = Convert.ToInt32(newSize.Height);

                Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));

                if (string.IsNullOrWhiteSpace(options.BackgroundColor))
                {
                    using (var originalImage = new MagickWand(originalImagePath))
                    {
                        originalImage.CurrentImage.ResizeImage(newWidth, newHeight);

                        DrawIndicator(originalImage, newWidth, newHeight, options);

                        originalImage.CurrentImage.CompressionQuality = quality;

                        originalImage.SaveImage(cacheFilePath);

                        return(cacheFilePath);
                    }
                }
                else
                {
                    using (var wand = new MagickWand(newWidth, newHeight, options.BackgroundColor))
                    {
                        using (var originalImage = new MagickWand(originalImagePath))
                        {
                            originalImage.CurrentImage.ResizeImage(newWidth, newHeight);

                            wand.CurrentImage.CompositeImage(originalImage, CompositeOperator.OverCompositeOp, 0, 0);
                            DrawIndicator(wand, newWidth, newHeight, options);

                            wand.CurrentImage.CompressionQuality = quality;

                            wand.SaveImage(cacheFilePath);

                            return(cacheFilePath);
                        }
                    }
                }
            }
            finally
            {
                semaphore.Release();
            }
        }
Beispiel #3
0
        public async Task ProcessImage(ImageProcessingOptions options, Stream toStream)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            if (toStream == null)
            {
                throw new ArgumentNullException("toStream");
            }

            var originalImagePath = options.OriginalImagePath;

            if (options.HasDefaultOptions() && options.Enhancers.Count == 0 && !options.CropWhiteSpace)
            {
                // Just spit out the original file if all the options are default
                using (var fileStream = _fileSystem.GetFileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
                {
                    await fileStream.CopyToAsync(toStream).ConfigureAwait(false);

                    return;
                }
            }

            var dateModified = options.OriginalImageDateModified;

            if (options.CropWhiteSpace)
            {
                var tuple = await GetWhitespaceCroppedImage(originalImagePath, dateModified).ConfigureAwait(false);

                originalImagePath = tuple.Item1;
                dateModified      = tuple.Item2;
            }

            if (options.Enhancers.Count > 0)
            {
                var tuple = await GetEnhancedImage(originalImagePath, dateModified, options.Item, options.ImageType, options.ImageIndex, options.Enhancers).ConfigureAwait(false);

                originalImagePath = tuple.Item1;
                dateModified      = tuple.Item2;
            }

            var originalImageSize = GetImageSize(originalImagePath, dateModified);

            // Determine the output size based on incoming parameters
            var newSize = DrawingUtils.Resize(originalImageSize, options.Width, options.Height, options.MaxWidth, options.MaxHeight);

            if (options.HasDefaultOptionsWithoutSize() && newSize.Equals(originalImageSize) && options.Enhancers.Count == 0)
            {
                // Just spit out the original file if the new size equals the old
                using (var fileStream = _fileSystem.GetFileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
                {
                    await fileStream.CopyToAsync(toStream).ConfigureAwait(false);

                    return;
                }
            }

            var quality = options.Quality ?? 90;

            var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, options.OutputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.BackgroundColor);

            try
            {
                using (var fileStream = _fileSystem.GetFileStream(cacheFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
                {
                    await fileStream.CopyToAsync(toStream).ConfigureAwait(false);

                    return;
                }
            }
            catch (IOException)
            {
                // Cache file doesn't exist or is currently being written to
            }

            var semaphore = GetLock(cacheFilePath);

            await semaphore.WaitAsync().ConfigureAwait(false);

            // Check again in case of lock contention
            try
            {
                using (var fileStream = _fileSystem.GetFileStream(cacheFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
                {
                    await fileStream.CopyToAsync(toStream).ConfigureAwait(false);

                    semaphore.Release();
                    return;
                }
            }
            catch (IOException)
            {
                // Cache file doesn't exist or is currently being written to
            }
            catch
            {
                semaphore.Release();
                throw;
            }

            try
            {
                var hasPostProcessing = !string.IsNullOrEmpty(options.BackgroundColor) || options.UnplayedCount.HasValue || options.AddPlayedIndicator || options.PercentPlayed.HasValue;

                //if (!hasPostProcessing)
                //{
                //    using (var outputStream = await _mediaEncoder.EncodeImage(new ImageEncodingOptions
                //    {
                //        InputPath = originalImagePath,
                //        MaxHeight = options.MaxHeight,
                //        MaxWidth = options.MaxWidth,
                //        Height = options.Height,
                //        Width = options.Width,
                //        Quality = options.Quality,
                //        Format = options.OutputFormat == ImageOutputFormat.Original ? Path.GetExtension(originalImagePath).TrimStart('.') : options.OutputFormat.ToString().ToLower()

                //    }, CancellationToken.None).ConfigureAwait(false))
                //    {
                //        using (var outputMemoryStream = new MemoryStream())
                //        {
                //            // Save to the memory stream
                //            await outputStream.CopyToAsync(outputMemoryStream).ConfigureAwait(false);

                //            var bytes = outputMemoryStream.ToArray();

                //            await toStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);

                //            // kick off a task to cache the result
                //            await CacheResizedImage(cacheFilePath, bytes).ConfigureAwait(false);
                //        }

                //        return;
                //    }
                //}

                using (var fileStream = _fileSystem.GetFileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
                {
                    // Copy to memory stream to avoid Image locking file
                    using (var memoryStream = new MemoryStream())
                    {
                        await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);

                        using (var originalImage = Image.FromStream(memoryStream, true, false))
                        {
                            var newWidth  = Convert.ToInt32(newSize.Width);
                            var newHeight = Convert.ToInt32(newSize.Height);

                            // Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here
                            using (var thumbnail = new Bitmap(newWidth, newHeight, PixelFormat.Format32bppPArgb))
                            {
                                // Mono throw an exeception if assign 0 to SetResolution
                                if (originalImage.HorizontalResolution > 0 && originalImage.VerticalResolution > 0)
                                {
                                    // Preserve the original resolution
                                    thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
                                }

                                using (var thumbnailGraph = Graphics.FromImage(thumbnail))
                                {
                                    thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
                                    thumbnailGraph.SmoothingMode      = SmoothingMode.HighQuality;
                                    thumbnailGraph.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                                    thumbnailGraph.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                                    thumbnailGraph.CompositingMode    = !hasPostProcessing ?
                                                                        CompositingMode.SourceCopy :
                                                                        CompositingMode.SourceOver;

                                    SetBackgroundColor(thumbnailGraph, options);

                                    thumbnailGraph.DrawImage(originalImage, 0, 0, newWidth, newHeight);

                                    DrawIndicator(thumbnailGraph, newWidth, newHeight, options);

                                    var outputFormat = GetOutputFormat(originalImage, options.OutputFormat);

                                    using (var outputMemoryStream = new MemoryStream())
                                    {
                                        // Save to the memory stream
                                        thumbnail.Save(outputFormat, outputMemoryStream, quality);

                                        var bytes = outputMemoryStream.ToArray();

                                        await toStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);

                                        // kick off a task to cache the result
                                        await CacheResizedImage(cacheFilePath, bytes).ConfigureAwait(false);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                semaphore.Release();
            }
        }
Beispiel #4
0
        public async Task <string> ProcessImage(ImageProcessingOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            var originalImagePath = options.Image.Path;

            if (options.HasDefaultOptions(originalImagePath) && options.Enhancers.Count == 0 && !options.CropWhiteSpace)
            {
                // Just spit out the original file if all the options are default
                return(originalImagePath);
            }

            var dateModified = options.Image.DateModified;
            var length       = options.Image.Length;

            if (options.CropWhiteSpace)
            {
                var tuple = await GetWhitespaceCroppedImage(originalImagePath, dateModified, length).ConfigureAwait(false);

                originalImagePath = tuple.Item1;
                dateModified      = tuple.Item2;
                length            = tuple.Item3;
            }

            if (options.Enhancers.Count > 0)
            {
                var tuple = await GetEnhancedImage(new ItemImageInfo
                {
                    Length       = length,
                    DateModified = dateModified,
                    Type         = options.Image.Type,
                    Path         = originalImagePath
                }, options.Item, options.ImageIndex, options.Enhancers).ConfigureAwait(false);

                originalImagePath = tuple.Item1;
                dateModified      = tuple.Item2;
                length            = tuple.Item3;
            }

            var originalImageSize = GetImageSize(originalImagePath, dateModified);

            // Determine the output size based on incoming parameters
            var newSize = DrawingUtils.Resize(originalImageSize, options.Width, options.Height, options.MaxWidth, options.MaxHeight);

            if (options.HasDefaultOptionsWithoutSize(originalImagePath) && newSize.Equals(originalImageSize) && options.Enhancers.Count == 0)
            {
                // Just spit out the original file if the new size equals the old
                return(originalImagePath);
            }

            var quality = options.Quality ?? 90;

            var outputFormat  = GetOutputFormat(options.OutputFormat);
            var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, length, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.BackgroundColor);

            var semaphore = GetLock(cacheFilePath);

            await semaphore.WaitAsync().ConfigureAwait(false);

            try
            {
                CheckDisposed();

                if (!File.Exists(cacheFilePath))
                {
                    var newWidth  = Convert.ToInt32(newSize.Width);
                    var newHeight = Convert.ToInt32(newSize.Height);

                    Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));

                    _imageEncoder.EncodeImage(originalImagePath, cacheFilePath, newWidth, newHeight, quality, options);
                }
            }
            finally
            {
                semaphore.Release();
            }

            return(cacheFilePath);
        }
Beispiel #5
0
        public async Task <string> ProcessImage(ImageProcessingOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            var originalImage = options.Image;

            if (!originalImage.IsLocalFile)
            {
                originalImage = await _libraryManager().ConvertImageToLocal(options.Item, originalImage, options.ImageIndex).ConfigureAwait(false);
            }

            var originalImagePath = originalImage.Path;

            if (!_imageEncoder.SupportsImageEncoding)
            {
                return(originalImagePath);
            }

            if (options.HasDefaultOptions(originalImagePath) && options.Enhancers.Count == 0 && !options.CropWhiteSpace)
            {
                // Just spit out the original file if all the options are default
                return(originalImagePath);
            }

            var dateModified = originalImage.DateModified;

            if (options.CropWhiteSpace && _imageEncoder.SupportsImageEncoding)
            {
                var tuple = await GetWhitespaceCroppedImage(originalImagePath, dateModified).ConfigureAwait(false);

                originalImagePath = tuple.Item1;
                dateModified      = tuple.Item2;
            }

            if (options.Enhancers.Count > 0)
            {
                var tuple = await GetEnhancedImage(new ItemImageInfo
                {
                    DateModified = dateModified,
                    Type         = originalImage.Type,
                    Path         = originalImagePath
                }, options.Item, options.ImageIndex, options.Enhancers).ConfigureAwait(false);

                originalImagePath = tuple.Item1;
                dateModified      = tuple.Item2;
            }

            var newSizeInfo   = GetNewImageSize(originalImagePath, dateModified, options);
            var newSize       = newSizeInfo.Item1;
            var isSizeChanged = newSizeInfo.Item2;

            if (options.HasDefaultOptionsWithoutSize(originalImagePath) && !isSizeChanged && options.Enhancers.Count == 0)
            {
                // Just spit out the original file if the new size equals the old
                return(originalImagePath);
            }

            var quality = options.Quality ?? 90;

            var outputFormat  = GetOutputFormat(options.OutputFormat);
            var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.BackgroundColor);

            var semaphore = GetLock(cacheFilePath);

            await semaphore.WaitAsync().ConfigureAwait(false);

            var imageProcessingLockTaken = false;

            try
            {
                CheckDisposed();

                if (!_fileSystem.FileExists(cacheFilePath))
                {
                    var newWidth  = Convert.ToInt32(newSize.Width);
                    var newHeight = Convert.ToInt32(newSize.Height);

                    _fileSystem.CreateDirectory(Path.GetDirectoryName(cacheFilePath));

                    await _imageProcessingSemaphore.WaitAsync().ConfigureAwait(false);

                    imageProcessingLockTaken = true;

                    _imageEncoder.EncodeImage(originalImagePath, cacheFilePath, newWidth, newHeight, quality, options);
                }
            }
            finally
            {
                if (imageProcessingLockTaken)
                {
                    _imageProcessingSemaphore.Release();
                }

                semaphore.Release();
            }

            return(cacheFilePath);
        }