Exemple #1
0
        /// <summary>
        ///     Search the gallery with a given query string.
        /// </summary>
        /// <param name="qAll">Search for all of these words (and).</param>
        /// <param name="qAny">Search for any of these words (or).</param>
        /// <param name="qExactly">Search for exactly this word or phrase.</param>
        /// <param name="qNot">Exclude results matching this word or phrase.</param>
        /// <param name="fileType">Show results for a specific file type.</param>
        /// <param name="imageSize">Show results for a specific image size.</param>
        /// <param name="sort">The order that the gallery should be sorted by. Default: Time</param>
        /// <param name="window">The time period that should be used in filtering requests. Default: Day</param>
        /// <param name="page">The data paging number. Default: null</param>
        /// <exception cref="ArgumentNullException">
        ///     Thrown when a null reference is passed to a method that does not accept it as a
        ///     valid argument.
        /// </exception>
        /// <exception cref="ImgurException">Thrown when an error is found in a response from an Imgur endpoint.</exception>
        /// <exception cref="MashapeException">Thrown when an error is found in a response from a Mashape endpoint.</exception>
        /// <returns></returns>
        public Basic<IEnumerable<GalleryItem>> SearchGalleryAdvanced(
            string qAll = null, string qAny = null,
            string qExactly = null, string qNot = null,
            ImageFileType? fileType = null, ImageSize? imageSize = null,
            GallerySortOrder? sort = GallerySortOrder.Time,
            TimeWindow? window = TimeWindow.All, int? page = null)
        {
            if (string.IsNullOrWhiteSpace(qAll) &&
                string.IsNullOrWhiteSpace(qAny) &&
                string.IsNullOrWhiteSpace(qExactly) &&
                string.IsNullOrWhiteSpace(qNot))
                throw new ArgumentNullException(null,
                    "At least one search parameter must be provided (All | Any | Exactly | Not).");

            sort = sort ?? GallerySortOrder.Time;
            window = window ?? TimeWindow.All;

            var sortValue = $"{sort}".ToLower();
            var windowValue = $"{window}".ToLower();

            var url = $"gallery/search/{sortValue}/{windowValue}/{page}";
            url = GalleryRequestBuilder.SearchGalleryAdvancedRequest(url, qAll, qAny, qExactly, qNot, fileType,
                imageSize);

            using (var request = RequestBuilderBase.CreateRequest(HttpMethod.Get, url))
            {
                var httpResponse = HttpClient.SendAsync(request).Result;
                var jsonString = httpResponse.Content.ReadAsStringAsync().Result;
                var output = Newtonsoft.Json.JsonConvert.DeserializeObject<Basic<IEnumerable<GalleryItem>>>(httpResponse.Content.ReadAsStringAsync().Result.ToString());
                return output;
            }
        }
Exemple #2
0
        public bool HasDefaultOptions(string originalImagePath, ImageSize?size)
        {
            if (!size.HasValue)
            {
                return(HasDefaultOptions(originalImagePath));
            }

            if (!HasDefaultOptionsWithoutSize(originalImagePath))
            {
                return(false);
            }

            var sizeValue = size.Value;

            if (Width.HasValue && !sizeValue.Width.Equals(Width.Value))
            {
                return(false);
            }
            if (Height.HasValue && !sizeValue.Height.Equals(Height.Value))
            {
                return(false);
            }
            if (MaxWidth.HasValue && sizeValue.Width > MaxWidth.Value)
            {
                return(false);
            }
            if (MaxHeight.HasValue && sizeValue.Height > MaxHeight.Value)
            {
                return(false);
            }

            return(true);
        }
Exemple #3
0
        /// <summary>
        ///     Search the gallery with a given query string.
        /// </summary>
        /// <param name="qAll">Search for all of these words (and).</param>
        /// <param name="qAny">Search for any of these words (or).</param>
        /// <param name="qExactly">Search for exactly this word or phrase.</param>
        /// <param name="qNot">Exclude results matching this word or phrase.</param>
        /// <param name="fileType">Show results for a specific file type.</param>
        /// <param name="imageSize">Show results for a specific image size.</param>
        /// <param name="sort">The order that the gallery should be sorted by. Default: Time</param>
        /// <param name="window">The time period that should be used in filtering requests. Default: Day</param>
        /// <param name="page">The data paging number. Default: null</param>
        /// <exception cref="ArgumentNullException">
        ///     Thrown when a null reference is passed to a method that does not accept it as a
        ///     valid argument.
        /// </exception>
        /// <exception cref="ImgurException">Thrown when an error is found in a response from an Imgur endpoint.</exception>
        /// <exception cref="MashapeException">Thrown when an error is found in a response from a Mashape endpoint.</exception>
        /// <returns></returns>
        public async Task <IEnumerable <IGalleryItem> > SearchGalleryAdvancedAsync(
            string qAll            = null, string qAny = null,
            string qExactly        = null, string qNot = null,
            ImageFileType?fileType = null, ImageSize?imageSize = null,
            GallerySortOrder?sort  = GallerySortOrder.Time,
            TimeWindow?window      = TimeWindow.All, int?page = null)
        {
            if (string.IsNullOrWhiteSpace(qAll) &&
                string.IsNullOrWhiteSpace(qAny) &&
                string.IsNullOrWhiteSpace(qExactly) &&
                string.IsNullOrWhiteSpace(qNot))
            {
                throw new ArgumentNullException(null,
                                                "At least one search parameter must be provided (All | Any | Exactly | Not).");
            }

            sort   = sort ?? GallerySortOrder.Time;
            window = window ?? TimeWindow.All;

            var sortValue   = $"{sort}".ToLower();
            var windowValue = $"{window}".ToLower();

            var url = $"gallery/search/{sortValue}/{windowValue}/{page}";

            url = GalleryRequestBuilder.SearchGalleryAdvancedRequest(url, qAll, qAny, qExactly, qNot, fileType,
                                                                     imageSize);

            using (var request = RequestBuilderBase.CreateRequest(HttpMethod.Get, url))
            {
                var searchResults = await SendRequestAsync <IEnumerable <GalleryItem> >(request).ConfigureAwait(false);

                return(searchResults);
            }
        }
Exemple #4
0
        public void EncodeImage(string inputPath, ImageSize?originalImageSize, string outputPath, bool autoOrient, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
        {
            using (var originalImage = GetImage(inputPath, options.CropWhiteSpace))
            {
                if (options.CropWhiteSpace || !originalImageSize.HasValue)
                {
                    originalImageSize = new ImageSize(originalImage.Width, originalImage.Height);
                }

                var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);

                var newWidth  = Convert.ToInt32(Math.Round(newImageSize.Width));
                var newHeight = Convert.ToInt32(Math.Round(newImageSize.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 = selectedOutputFormat == ImageFormat.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;

                        // SourceCopy causes the image to be blank in OSX
                        //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, selectedOutputFormat);

                        // Save to the cache location
                        using (var cacheFileStream = _fileSystem.GetFileStream(outputPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, false))
                        {
                            // Save to the memory stream
                            thumbnail.Save(outputFormat, cacheFileStream, quality);
                        }
                    }
                }
            }
        }
Exemple #5
0
        private ImageSize GetNewImageSize(ImageProcessingOptions options, ImageSize?originalImageSize)
        {
            if (originalImageSize.HasValue)
            {
                // Determine the output size based on incoming parameters
                var newSize = DrawingUtils.Resize(originalImageSize.Value, options.Width, options.Height, options.MaxWidth, options.MaxHeight);

                return(newSize);
            }
            return(GetSizeEstimate(options));
        }
        public static string GetUrl(ImageSize?size, string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                fileName = YunClient.WebUrl + "/content/images/none-image.png";
            }

            //输入的文件名是否包http,如果不包含,则需要增加前缀
            if (!fileName.StartsWith("http"))
            {
                fileName = string.Format("{0}{1}{2}", YunClient.WebUrl, FilesUpload.ImageFolder, fileName);
            }

            return(size == null
                ? fileName
                : InsertAtEndOfFileName(fileName, _imageFileSizeDictionary[(ImageSize)size]));
        }
Exemple #7
0
        /// <exception cref="T:System.ArgumentNullException">
        ///     Thrown when a null reference is passed to a method that does not accept it as a
        ///     valid argument.
        /// </exception>
        internal string SearchGalleryAdvancedRequest(
            string url,
            string qAll            = null,
            string qAny            = null,
            string qExactly        = null,
            string qNot            = null,
            ImageFileType?fileType = null,
            ImageSize?imageSize    = null)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                throw new ArgumentNullException(nameof(url));
            }
            if (string.IsNullOrWhiteSpace(qAll) && string.IsNullOrWhiteSpace(qAny) && string.IsNullOrWhiteSpace(qExactly) && string.IsNullOrWhiteSpace(qNot))
            {
                throw new ArgumentNullException((string)null, "At least one search parameter must be provided (All | Any | Exactly | Not).");
            }
            StringBuilder stringBuilder = new StringBuilder();

            if (!string.IsNullOrWhiteSpace(qAll))
            {
                stringBuilder.Append(string.Format("&q_all={0}", (object)WebUtility.UrlEncode(qAll)));
            }
            if (!string.IsNullOrWhiteSpace(qAny))
            {
                stringBuilder.Append(string.Format("&q_any={0}", (object)WebUtility.UrlEncode(qAny)));
            }
            if (!string.IsNullOrWhiteSpace(qExactly))
            {
                stringBuilder.Append(string.Format("&q_exactly={0}", (object)WebUtility.UrlEncode(qExactly)));
            }
            if (!string.IsNullOrWhiteSpace(qNot))
            {
                stringBuilder.Append(string.Format("&q_not={0}", (object)WebUtility.UrlEncode(qNot)));
            }
            if (fileType.HasValue)
            {
                stringBuilder.Append(string.Format("&q_type={0}", (object)WebUtility.UrlEncode(fileType.ToString().ToLower())));
            }
            if (imageSize.HasValue)
            {
                stringBuilder.Append(string.Format("&q_size_px={0}", (object)WebUtility.UrlEncode(imageSize.ToString().ToLower())));
            }
            return(string.Format("{0}?{1}", (object)url, (object)stringBuilder).Replace("?&", "?"));
        }
Exemple #8
0
        /// <summary>Search the gallery with a given query string.</summary>
        /// <param name="qAll">Search for all of these words (and).</param>
        /// <param name="qAny">Search for any of these words (or).</param>
        /// <param name="qExactly">Search for exactly this word or phrase.</param>
        /// <param name="qNot">Exclude results matching this word or phrase.</param>
        /// <param name="fileType">Show results for a specific file type.</param>
        /// <param name="imageSize">Show results for a specific image size.</param>
        /// <param name="sort">The order that the gallery should be sorted by. Default: Time</param>
        /// <param name="window">The time period that should be used in filtering requests. Default: Day</param>
        /// <param name="page">The data paging number. Default: null</param>
        /// <exception cref="T:System.ArgumentNullException">
        ///     Thrown when a null reference is passed to a method that does not accept it as a
        ///     valid argument.
        /// </exception>
        /// <exception cref="T:Imgur.API.ImgurException">Thrown when an error is found in a response from an Imgur endpoint.</exception>
        /// <exception cref="T:Imgur.API.MashapeException">Thrown when an error is found in a response from a Mashape endpoint.</exception>
        /// <returns></returns>
        public async Task <IEnumerable <IGalleryItem> > SearchGalleryAdvancedAsync(
            string qAll            = null,
            string qAny            = null,
            string qExactly        = null,
            string qNot            = null,
            ImageFileType?fileType = null,
            ImageSize?imageSize    = null,
            GallerySortOrder?sort  = GallerySortOrder.Time,
            TimeWindow?window      = TimeWindow.All,
            int?page = null)
        {
            if (string.IsNullOrWhiteSpace(qAll) && string.IsNullOrWhiteSpace(qAny) && string.IsNullOrWhiteSpace(qExactly) && string.IsNullOrWhiteSpace(qNot))
            {
                throw new ArgumentNullException((string)null, "At least one search parameter must be provided (All | Any | Exactly | Not).");
            }
            GallerySortOrder?nullable1 = sort;

            sort = new GallerySortOrder?(nullable1.HasValue ? nullable1.GetValueOrDefault() : GallerySortOrder.Time);
            TimeWindow?nullable2 = window;

            window = new TimeWindow?(nullable2.HasValue ? nullable2.GetValueOrDefault() : TimeWindow.All);
            string sortValue   = string.Format("{0}", (object)sort).ToLower();
            string windowValue = string.Format("{0}", (object)window).ToLower();
            string url         = string.Format("gallery/search/{0}/{1}/{2}", (object)sortValue, (object)windowValue, (object)page);

            url = this.RequestBuilder.SearchGalleryAdvancedRequest(url, qAll, qAny, qExactly, qNot, fileType, imageSize);
            IEnumerable <IGalleryItem> galleryItems;

            using (HttpRequestMessage request = this.RequestBuilder.CreateRequest(HttpMethod.Get, url))
            {
                IEnumerable <GalleryItem> searchResults = await this.SendRequestAsync <IEnumerable <GalleryItem> >(request).ConfigureAwait(false);

                galleryItems = (IEnumerable <IGalleryItem>)searchResults;
            }
            return(galleryItems);
        }
Exemple #9
0
        public async Task <Tuple <string, string, DateTime> > ProcessImage(ImageProcessingOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            var          originalImage = options.Image;
            IHasMetadata item          = options.Item;

            if (!originalImage.IsLocalFile)
            {
                if (item == null)
                {
                    item = _libraryManager().GetItemById(options.ItemId);
                }
                originalImage = await _libraryManager().ConvertImageToLocal(item, originalImage, options.ImageIndex).ConfigureAwait(false);
            }

            var originalImagePath = originalImage.Path;
            var dateModified      = originalImage.DateModified;

            if (!_imageEncoder.SupportsImageEncoding)
            {
                return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified));
            }

            var supportedImageInfo = await GetSupportedImage(originalImagePath, dateModified).ConfigureAwait(false);

            originalImagePath = supportedImageInfo.Item1;
            dateModified      = supportedImageInfo.Item2;
            var requiresTransparency = TransparentImageTypes.Contains(Path.GetExtension(originalImagePath) ?? string.Empty);

            if (options.Enhancers.Count > 0)
            {
                if (item == null)
                {
                    item = _libraryManager().GetItemById(options.ItemId);
                }

                var tuple = await GetEnhancedImage(new ItemImageInfo
                {
                    DateModified = dateModified,
                    Type         = originalImage.Type,
                    Path         = originalImagePath
                }, requiresTransparency, item, options.ImageIndex, options.Enhancers).ConfigureAwait(false);

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

            var photo      = item as Photo;
            var autoOrient = false;
            ImageOrientation?orientation = null;

            if (photo != null && photo.Orientation.HasValue && photo.Orientation.Value != ImageOrientation.TopLeft)
            {
                autoOrient  = true;
                orientation = photo.Orientation;
            }

            if (options.HasDefaultOptions(originalImagePath) && (!autoOrient || !options.RequiresAutoOrientation))
            {
                // Just spit out the original file if all the options are default
                return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified));
            }

            ImageSize?originalImageSize = GetSavedImageSize(originalImagePath, dateModified);

            if (originalImageSize.HasValue && options.HasDefaultOptions(originalImagePath, originalImageSize.Value) && !autoOrient)
            {
                // Just spit out the original file if all the options are default
                _logger.Info("Returning original image {0}", originalImagePath);
                return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified));
            }

            var newSize = ImageHelper.GetNewImageSize(options, originalImageSize);
            var quality = options.Quality;

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

            try
            {
                CheckDisposed();

                if (!_fileSystem.FileExists(cacheFilePath))
                {
                    var tmpPath = Path.ChangeExtension(Path.Combine(_appPaths.TempDirectory, Guid.NewGuid().ToString("N")), Path.GetExtension(cacheFilePath));
                    _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(tmpPath));

                    if (options.CropWhiteSpace && !SupportsTransparency(originalImagePath))
                    {
                        options.CropWhiteSpace = false;
                    }

                    var resultPath = _imageEncoder.EncodeImage(originalImagePath, dateModified, tmpPath, autoOrient, orientation, quality, options, outputFormat);

                    if (string.Equals(resultPath, originalImagePath, StringComparison.OrdinalIgnoreCase))
                    {
                        return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified));
                    }

                    _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(cacheFilePath));
                    CopyFile(tmpPath, cacheFilePath);

                    return(new Tuple <string, string, DateTime>(tmpPath, GetMimeType(outputFormat, cacheFilePath), _fileSystem.GetLastWriteTimeUtc(tmpPath)));
                }

                return(new Tuple <string, string, DateTime>(cacheFilePath, GetMimeType(outputFormat, cacheFilePath), _fileSystem.GetLastWriteTimeUtc(cacheFilePath)));
            }
            catch (ArgumentOutOfRangeException ex)
            {
                // Decoder failed to decode it
#if DEBUG
                _logger.ErrorException("Error encoding image", ex);
#endif
                // Just spit out the original file if all the options are default
                return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified));
            }
            catch (Exception ex)
            {
                // If it fails for whatever reason, return the original image
                _logger.ErrorException("Error encoding image", ex);

                // Just spit out the original file if all the options are default
                return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified));
            }
        }
Exemple #10
0
        private void ProcessArgv(string[] argv)
        {
            _useStdin  = true;
            _inputFile = _outputFile = null;
            _format    = null;
            _size      = null;
            _quality   = null;
            _threads   = null;

            NoLogo = false;
            Plugin = new string[0];

            var lastarg = argv.Length - 1;

            for (var i = 0; i < argv.Length - 1; i++)
            {
                switch (argv[i])
                {
                case "--help":
                case "-h":
                    Usage(Console.Out);
                    Environment.Exit(0);
                    break;

                case "--nologo":
                    NoLogo = true;
                    break;

                case "--input":
                case "-i":
                    _inputFile = argv.ElementAtOrDefault(i + 1);
                    if (string.IsNullOrWhiteSpace(_inputFile))
                    {
                        Console.Error.WriteLine("Missing parameter for -i/--input.");
                        Usage(Console.Error);
                        Environment.Exit(1);
                    }
                    _useStdin = false;
                    ++i; break;

                case "--format":
                case "-f":
                    if (!Enum.TryParse <ImageFormat>(argv.ElementAtOrDefault(i + 1) ?? "", true, out var fmt))
                    {
                        Console.Error.WriteLine("Invalid format. Supported formats: " + string.Join(", ", Enum.GetValues(typeof(ImageFormat)).OfType <ImageFormat>().Select(x => x.ToString().ToLowerInvariant())));
                        Usage(Console.Error);
                        Environment.Exit(1);
                    }
                    _format = fmt;
                    ++i; break;

                case "--size":
                case "-s":
                    var spl = (argv.ElementAtOrDefault(i + 1) ?? "").Split('x');
                    if (spl.Length != 2 || !spl.All(x => int.TryParse(x, out _)))
                    {
                        Console.Error.WriteLine("Invalid size definition. Please use a lowercase 'x' to separate width and height.");
                        Usage(Console.Error);
                        Environment.Exit(1);
                    }
                    _size = new ImageSize(int.Parse(spl[0]), int.Parse(spl[1]));
                    ++i; break;

                case "--quality":
                case "-q":
                    if (!double.TryParse(argv.ElementAtOrDefault(i + 1) ?? "", NumberStyles.Float, CultureInfo.InvariantCulture, out var q) || q <= 0)
                    {
                        Console.Error.WriteLine("Invalid quality definition. Please use a notation like '1.23' or '10e3' and give a value larger than zero.");
                        Usage(Console.Error);
                        Environment.Exit(1);
                    }
                    _quality = q;
                    ++i; break;

                case "--threads":
                case "-mt":
                    if (!int.TryParse(argv.ElementAtOrDefault(i + 1) ?? "", out var t) || t < 1)
                    {
                        Console.Error.WriteLine("Invalid thread count. Please give a value larger than or equal to 1.");
                        Usage(Console.Error);
                        Environment.Exit(1);
                    }
                    _threads = t;
                    ++i; break;

                case "--plugin":
                    var pglob = argv.ElementAtOrDefault(i + 1);
                    if (string.IsNullOrWhiteSpace(pglob))
                    {
                        Console.Error.WriteLine("Missing parameter for --plugin.");
                        Usage(Console.Error);
                        Environment.Exit(1);
                    }
                    Plugin = Plugin.Concat(new[] { pglob }).ToArray();
                    ++i; break;

                case "--":
                    lastarg = i + 1;
                    break;

                default:
                    Console.Error.WriteLine("Argument not expected: " + argv[i]);
                    Usage(Console.Error);
                    Environment.Exit(1);
                    break;
                }
            }

            _outputFile = argv.ElementAtOrDefault(lastarg);
            if (string.IsNullOrWhiteSpace(_outputFile))
            {
                Console.Error.WriteLine("Please give an output file.");
                Usage(Console.Error);
                Environment.Exit(1);
            }

            if (_format == null)
            {
                var ext = Path.GetExtension(_outputFile).TrimStart('.').ToLowerInvariant();
                if (ext == "jpeg")
                {
                    ext = "jpg";
                }

                if (!Enum.TryParse <ImageFormat>(ext, true, out var fmt))
                {
                    _outputFile += ".bmp";
                    _format      = ImageFormat.Bmp;
                }
                else
                {
                    _format = fmt;
                }
            }
        }
Exemple #11
0
        internal static string SearchGalleryAdvancedRequest(string url,
                                                            string qAll            = null, string qAny = null,
                                                            string qExactly        = null, string qNot = null,
                                                            ImageFileType?fileType = null, ImageSize?imageSize = null)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                throw new ArgumentNullException(nameof(url));
            }

            if (string.IsNullOrWhiteSpace(qAll) &&
                string.IsNullOrWhiteSpace(qAny) &&
                string.IsNullOrWhiteSpace(qExactly) &&
                string.IsNullOrWhiteSpace(qNot))
            {
                throw new ArgumentNullException(null,
                                                "At least one search parameter must be provided (All | Any | Exactly | Not).");
            }

            var query = new StringBuilder();

            if (!string.IsNullOrWhiteSpace(qAll))
            {
                query.Append($"&q_all={WebUtility.UrlEncode(qAll)}");
            }

            if (!string.IsNullOrWhiteSpace(qAny))
            {
                query.Append($"&q_any={WebUtility.UrlEncode(qAny)}");
            }

            if (!string.IsNullOrWhiteSpace(qExactly))
            {
                query.Append($"&q_exactly={WebUtility.UrlEncode(qExactly)}");
            }

            if (!string.IsNullOrWhiteSpace(qNot))
            {
                query.Append($"&q_not={WebUtility.UrlEncode(qNot)}");
            }

            if (fileType != null)
            {
                query.Append($"&q_type={WebUtility.UrlEncode(fileType.ToString().ToLower())}");
            }

            if (imageSize != null)
            {
                query.Append($"&q_size_px={WebUtility.UrlEncode(imageSize.ToString().ToLower())}");
            }

            return($"{url}?{query}".Replace("?&", "?"));
        }
Exemple #12
0
        public async Task <Tuple <string, string, DateTime> > ProcessImage(ImageProcessingOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            var        originalImage = options.Image;
            IHasImages item          = options.Item;

            if (!originalImage.IsLocalFile)
            {
                if (item == null)
                {
                    item = _libraryManager().GetItemById(options.ItemId);
                }
                originalImage = await _libraryManager().ConvertImageToLocal(item, originalImage, options.ImageIndex).ConfigureAwait(false);
            }

            var originalImagePath = originalImage.Path;
            var dateModified      = originalImage.DateModified;

            if (!_imageEncoder.SupportsImageEncoding)
            {
                return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified));
            }

            if (options.Enhancers.Count > 0)
            {
                if (item == null)
                {
                    item = _libraryManager().GetItemById(options.ItemId);
                }

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

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

            if (options.HasDefaultOptions(originalImagePath))
            {
                // Just spit out the original file if all the options are default
                return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified));
            }

            ImageSize?originalImageSize = GetSavedImageSize(originalImagePath, dateModified);

            if (originalImageSize.HasValue && options.HasDefaultOptions(originalImagePath, originalImageSize.Value))
            {
                // Just spit out the original file if all the options are default
                _logger.Info("Returning original image {0}", originalImagePath);
                return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified));
            }

            var newSize = ImageHelper.GetNewImageSize(options, originalImageSize);
            var quality = options.Quality;

            var outputFormat  = GetOutputFormat(options.SupportedOutputFormats[0]);
            var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.Blur, options.BackgroundColor, options.ForegroundLayer);

            try
            {
                CheckDisposed();

                if (!_fileSystem.FileExists(cacheFilePath))
                {
                    _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(cacheFilePath));
                    var tmpPath = Path.ChangeExtension(Path.Combine(_appPaths.TempDirectory, Guid.NewGuid().ToString("N")), Path.GetExtension(cacheFilePath));
                    _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(tmpPath));

                    if (item == null && string.Equals(options.ItemType, typeof(Photo).Name, StringComparison.OrdinalIgnoreCase))
                    {
                        item = _libraryManager().GetItemById(options.ItemId);
                    }

                    var resultPath = _imageEncoder.EncodeImage(originalImagePath, dateModified, tmpPath, AutoOrient(item), quality, options, outputFormat);

                    if (string.Equals(resultPath, originalImagePath, StringComparison.OrdinalIgnoreCase))
                    {
                        return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified));
                    }

                    CopyFile(tmpPath, cacheFilePath);

                    return(new Tuple <string, string, DateTime>(tmpPath, GetMimeType(outputFormat, cacheFilePath), _fileSystem.GetLastWriteTimeUtc(tmpPath)));
                }

                return(new Tuple <string, string, DateTime>(cacheFilePath, GetMimeType(outputFormat, cacheFilePath), _fileSystem.GetLastWriteTimeUtc(cacheFilePath)));
            }
            catch (Exception ex)
            {
                // If it fails for whatever reason, return the original image
                _logger.ErrorException("Error encoding image", ex);

                // Just spit out the original file if all the options are default
                return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified));
            }
        }
Exemple #13
0
    public static string Image(string fileKey, ImageSize?imageSize = ImageSize.MD)
    {
        var size = imageSize.HasValue ? imageSize.Value.ToSuffix() : "";

        return(Config.ImageBaseUrl + fileKey + size);
    }