private ImageInfo GetImageInfo(IHasImages item, ItemImageInfo info, int?imageIndex)
        {
            try
            {
                var fileInfo = new FileInfo(info.Path);

                var size = _imageProcessor.GetImageSize(info.Path);

                return(new ImageInfo
                {
                    Path = info.Path,
                    ImageIndex = imageIndex,
                    ImageType = info.Type,
                    ImageTag = _imageProcessor.GetImageCacheTag(item, info),
                    Size = fileInfo.Length,
                    Width = Convert.ToInt32(size.Width),
                    Height = Convert.ToInt32(size.Height)
                });
            }
            catch (Exception ex)
            {
                Logger.ErrorException("Error getting image information for {0}", ex, info.Path);

                return(null);
            }
        }
Beispiel #2
0
        /// <summary>
        /// Attaches the primary image aspect ratio.
        /// </summary>
        /// <param name="dto">The dto.</param>
        /// <param name="item">The item.</param>
        /// <returns>Task.</returns>
        public void AttachPrimaryImageAspectRatio(IItemDto dto, IHasImages item)
        {
            var imageInfo = item.GetImageInfo(ImageType.Primary, 0);

            if (imageInfo == null)
            {
                return;
            }

            var path = imageInfo.Path;

            // See if we can avoid a file system lookup by looking for the file in ResolveArgs
            var dateModified = imageInfo.DateModified;

            ImageSize size;

            try
            {
                size = _imageProcessor.GetImageSize(path, dateModified);
            }
            catch (FileNotFoundException)
            {
                _logger.Error("Image file does not exist: {0}", path);
                return;
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
                return;
            }

            dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;

            var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();

            foreach (var enhancer in supportedEnhancers)
            {
                try
                {
                    size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
                }
            }

            dto.PrimaryImageAspectRatio = size.Width / size.Height;
        }
        private double GetResolution(BaseItem item, string path)
        {
            try
            {
                var date = item.GetImageDateModified(path);

                var size = _imageProcessor.GetImageSize(path, date);

                return(size.Width);
            }
            catch
            {
                return(0);
            }
        }
        private double GetResolution(BaseItem item, ImageType type, int index)
        {
            try
            {
                var info = item.GetImageInfo(type, index);

                var size = _imageProcessor.GetImageSize(info.Path, info.DateModified);

                return(size.Width);
            }
            catch
            {
                return(0);
            }
        }
Beispiel #5
0
        private ImageInfo GetImageInfo(BaseItem item, ItemImageInfo info, int?imageIndex)
        {
            try
            {
                int? width  = null;
                int? height = null;
                long length = 0;

                try
                {
                    if (info.IsLocalFile)
                    {
                        var fileInfo = _fileSystem.GetFileInfo(info.Path);
                        length = fileInfo.Length;

                        var size = _imageProcessor.GetImageSize(item, info, true, true);

                        width  = Convert.ToInt32(size.Width);
                        height = Convert.ToInt32(size.Height);

                        if (width <= 0 || height <= 0)
                        {
                            width  = null;
                            height = null;
                        }
                    }
                }
                catch
                {
                }
                return(new ImageInfo
                {
                    Path = info.Path,
                    ImageIndex = imageIndex,
                    ImageType = info.Type,
                    ImageTag = _imageProcessor.GetImageCacheTag(item, info),
                    Size = length,
                    Width = width,
                    Height = height
                });
            }
            catch (Exception ex)
            {
                Logger.ErrorException("Error getting image information for {0}", ex, info.Path);

                return(null);
            }
        }
Beispiel #6
0
        private ImageDownloadInfo GetImageInfo(BaseItem item, ImageType type)
        {
            var    imageInfo = item.GetImageInfo(type, 0);
            string tag       = null;

            try
            {
                tag = _imageProcessor.GetImageCacheTag(item, type);
            }
            catch
            {
            }

            int?width  = null;
            int?height = null;

            try
            {
                var size = _imageProcessor.GetImageSize(imageInfo);

                width  = Convert.ToInt32(size.Width);
                height = Convert.ToInt32(size.Height);
            }
            catch
            {
            }

            var inputFormat = (Path.GetExtension(imageInfo.Path) ?? string.Empty)
                              .TrimStart('.')
                              .Replace("jpeg", "jpg", StringComparison.OrdinalIgnoreCase);

            return(new ImageDownloadInfo
            {
                ItemId = item.Id.ToString("N"),
                Type = type,
                ImageTag = tag,
                Width = width,
                Height = height,
                Format = inputFormat,
                ItemImageInfo = imageInfo
            });
        }
Beispiel #7
0
        private ImageDownloadInfo GetImageInfo(BaseItem item, ImageType type)
        {
            var    imageInfo = item.GetImageInfo(type, 0);
            string tag       = null;

            try
            {
                tag = _imageProcessor.GetImageCacheTag(item, type);
            }
            catch
            {
            }

            int?width  = null;
            int?height = null;

            try
            {
                var size = _imageProcessor.GetImageSize(imageInfo.Path, imageInfo.DateModified);

                width  = Convert.ToInt32(size.Width);
                height = Convert.ToInt32(size.Height);
            }
            catch
            {
            }

            return(new ImageDownloadInfo
            {
                ItemId = item.Id.ToString("N"),
                Type = type,
                ImageTag = tag,
                Width = width,
                Height = height,
                File = imageInfo.Path,
                ItemImageInfo = imageInfo
            });
        }
Beispiel #8
0
        private ImageDownloadInfo GetImageInfo(BaseItem item, ImageType type)
        {
            var    imageInfo = item.GetImageInfo(type, 0);
            string tag       = null;

            try
            {
                var guid = _imageProcessor.GetImageCacheTag(item, ImageType.Primary);

                tag = guid.HasValue ? guid.Value.ToString("N") : null;
            }
            catch
            {
            }

            int?width  = null;
            int?height = null;

            try
            {
                var size = _imageProcessor.GetImageSize(imageInfo.Path, imageInfo.DateModified);

                width  = Convert.ToInt32(size.Width);
                height = Convert.ToInt32(size.Height);
            }
            catch
            {
            }

            return(new ImageDownloadInfo
            {
                ItemId = item.Id.ToString("N"),
                Type = ImageType.Primary,
                ImageTag = tag,
                Width = width,
                Height = height
            });
        }
        public void Optimize(ISiGamePack pack)
        {
            var assets = pack.ImageAssets.ToArray();
            var n      = assets.Length;

            Log.Information($"ImageSizeReducer started. {n} assets to optimize");
            for (var i = 0; i < assets.Length; i++)
            {
                Log.Information($"ImageSizeReducer {i+1} / {n}: {assets[i].Name}");
                if (!_mimeWorker.IsImage(assets[i].Content))
                {
                    continue;
                }
                var originalSize = _imageProcessor.GetImageSize(assets[i].Content);
                var newSize      = CalculateNewSize(originalSize);
                var newAsset     = new Asset
                {
                    Name    = assets[i].Name,
                    Type    = assets[i].Type,
                    Content = _imageProcessor.EncodeImage(assets[i].Content, newSize, _settings.JpegQuality)
                };
                pack.InsertAsset(newAsset);
            }
        }
Beispiel #10
0
        public Task <ItemUpdateType> FetchAsync(Photo item, MetadataRefreshOptions options, CancellationToken cancellationToken)
        {
            item.SetImagePath(ImageType.Primary, item.Path);

            // Examples: https://github.com/mono/taglib-sharp/blob/a5f6949a53d09ce63ee7495580d6802921a21f14/tests/fixtures/TagLib.Tests.Images/NullOrientationTest.cs
            if (!_excludeExtensions.Contains(Path.GetExtension(item.Path) ?? string.Empty, StringComparer.OrdinalIgnoreCase))
            {
                try
                {
                    using (var fileStream = _fileSystem.OpenRead(item.Path))
                    {
                        using (var file = TagLib.File.Create(new StreamFileAbstraction(Path.GetFileName(item.Path), fileStream, null)))
                        {
                            var image = file as TagLib.Image.File;

                            var tag = file.GetTag(TagTypes.TiffIFD) as IFDTag;

                            if (tag != null)
                            {
                                var structure = tag.Structure;

                                if (structure != null)
                                {
                                    var exif = structure.GetEntry(0, (ushort)IFDEntryTag.ExifIFD) as SubIFDEntry;

                                    if (exif != null)
                                    {
                                        var exifStructure = exif.Structure;

                                        if (exifStructure != null)
                                        {
                                            var entry = exifStructure.GetEntry(0, (ushort)ExifEntryTag.ApertureValue) as RationalIFDEntry;

                                            if (entry != null)
                                            {
                                                double val = entry.Value.Numerator;
                                                val          /= entry.Value.Denominator;
                                                item.Aperture = val;
                                            }

                                            entry = exifStructure.GetEntry(0, (ushort)ExifEntryTag.ShutterSpeedValue) as RationalIFDEntry;

                                            if (entry != null)
                                            {
                                                double val = entry.Value.Numerator;
                                                val /= entry.Value.Denominator;
                                                item.ShutterSpeed = val;
                                            }
                                        }
                                    }
                                }
                            }

                            if (image != null)
                            {
                                item.CameraMake  = image.ImageTag.Make;
                                item.CameraModel = image.ImageTag.Model;

                                item.Width  = image.Properties.PhotoWidth;
                                item.Height = image.Properties.PhotoHeight;

                                var rating = image.ImageTag.Rating;
                                if (rating.HasValue)
                                {
                                    item.CommunityRating = rating;
                                }
                                else
                                {
                                    item.CommunityRating = null;
                                }

                                item.Overview = image.ImageTag.Comment;

                                if (!string.IsNullOrWhiteSpace(image.ImageTag.Title))
                                {
                                    item.Name = image.ImageTag.Title;
                                }

                                var dateTaken = image.ImageTag.DateTime;
                                if (dateTaken.HasValue)
                                {
                                    item.DateCreated    = dateTaken.Value;
                                    item.PremiereDate   = dateTaken.Value;
                                    item.ProductionYear = dateTaken.Value.Year;
                                }

                                item.Genres   = image.ImageTag.Genres.ToList();
                                item.Tags     = image.ImageTag.Keywords;
                                item.Software = image.ImageTag.Software;

                                if (image.ImageTag.Orientation == TagLib.Image.ImageOrientation.None)
                                {
                                    item.Orientation = null;
                                }
                                else
                                {
                                    MediaBrowser.Model.Drawing.ImageOrientation orientation;
                                    if (Enum.TryParse(image.ImageTag.Orientation.ToString(), true, out orientation))
                                    {
                                        item.Orientation = orientation;
                                    }
                                }

                                item.ExposureTime = image.ImageTag.ExposureTime;
                                item.FocalLength  = image.ImageTag.FocalLength;

                                item.Latitude  = image.ImageTag.Latitude;
                                item.Longitude = image.ImageTag.Longitude;
                                item.Altitude  = image.ImageTag.Altitude;

                                if (image.ImageTag.ISOSpeedRatings.HasValue)
                                {
                                    item.IsoSpeedRating = Convert.ToInt32(image.ImageTag.ISOSpeedRatings.Value);
                                }
                                else
                                {
                                    item.IsoSpeedRating = null;
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    _logger.ErrorException("Image Provider - Error reading image tag for {0}", e, item.Path);
                }
            }

            if (!item.Width.HasValue || !item.Height.HasValue)
            {
                var size = _imageProcessor.GetImageSize(item.Path);

                item.Width  = Convert.ToInt32(size.Width);
                item.Height = Convert.ToInt32(size.Height);
            }

            const ItemUpdateType result = ItemUpdateType.ImageUpdate | ItemUpdateType.MetadataImport;

            return(Task.FromResult(result));
        }
Beispiel #11
0
        public double?GetPrimaryImageAspectRatio(BaseItem item)
        {
            var imageInfo = item.GetImageInfo(ImageType.Primary, 0);

            if (imageInfo == null)
            {
                return(null);
            }

            var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary);

            ImageSize size;

            var defaultAspectRatio = item.GetDefaultPrimaryImageAspectRatio();

            if (defaultAspectRatio > 0)
            {
                if (supportedEnhancers.Length == 0)
                {
                    return(defaultAspectRatio);
                }

                double dummyWidth  = 200;
                double dummyHeight = dummyWidth / defaultAspectRatio;
                size = new ImageSize(dummyWidth, dummyHeight);
            }
            else
            {
                if (!imageInfo.IsLocalFile)
                {
                    return(null);
                }

                try
                {
                    size = _imageProcessor.GetImageSize(item, imageInfo);

                    if (size.Width <= 0 || size.Height <= 0)
                    {
                        return(null);
                    }
                }
                catch (Exception ex)
                {
                    //_logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, imageInfo.Path);
                    return(null);
                }
            }

            foreach (var enhancer in supportedEnhancers)
            {
                try
                {
                    size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
                }
            }

            var width  = size.Width;
            var height = size.Height;

            if (width.Equals(0) || height.Equals(0))
            {
                return(null);
            }

            return(width / height);
        }
Beispiel #12
0
        /// <summary>
        /// Gets the item image infos.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns>Task{List{ImageInfo}}.</returns>
        public List <ImageInfo> GetItemImageInfos(BaseItem item)
        {
            var list = new List <ImageInfo>();

            foreach (var image in item.Images)
            {
                var path = image.Value;

                var fileInfo = new FileInfo(path);

                var size = _imageProcessor.GetImageSize(path);

                list.Add(new ImageInfo
                {
                    Path      = path,
                    ImageType = image.Key,
                    ImageTag  = _imageProcessor.GetImageCacheTag(item, image.Key, path),
                    Size      = fileInfo.Length,
                    Width     = Convert.ToInt32(size.Width),
                    Height    = Convert.ToInt32(size.Height)
                });
            }

            var index = 0;

            foreach (var image in item.BackdropImagePaths)
            {
                var fileInfo = new FileInfo(image);

                var size = _imageProcessor.GetImageSize(image);

                list.Add(new ImageInfo
                {
                    Path       = image,
                    ImageIndex = index,
                    ImageType  = ImageType.Backdrop,
                    ImageTag   = _imageProcessor.GetImageCacheTag(item, ImageType.Backdrop, image),
                    Size       = fileInfo.Length,
                    Width      = Convert.ToInt32(size.Width),
                    Height     = Convert.ToInt32(size.Height)
                });

                index++;
            }

            index = 0;

            foreach (var image in item.ScreenshotImagePaths)
            {
                var fileInfo = new FileInfo(image);

                var size = _imageProcessor.GetImageSize(image);

                list.Add(new ImageInfo
                {
                    Path       = image,
                    ImageIndex = index,
                    ImageType  = ImageType.Screenshot,
                    ImageTag   = _imageProcessor.GetImageCacheTag(item, ImageType.Screenshot, image),
                    Size       = fileInfo.Length,
                    Width      = Convert.ToInt32(size.Width),
                    Height     = Convert.ToInt32(size.Height)
                });

                index++;
            }

            var video = item as Video;

            if (video != null)
            {
                index = 0;

                foreach (var chapter in _itemRepo.GetChapters(video.Id))
                {
                    if (!string.IsNullOrEmpty(chapter.ImagePath))
                    {
                        var image = chapter.ImagePath;

                        var fileInfo = new FileInfo(image);

                        var size = _imageProcessor.GetImageSize(image);

                        list.Add(new ImageInfo
                        {
                            Path       = image,
                            ImageIndex = index,
                            ImageType  = ImageType.Chapter,
                            ImageTag   = _imageProcessor.GetImageCacheTag(item, ImageType.Chapter, image),
                            Size       = fileInfo.Length,
                            Width      = Convert.ToInt32(size.Width),
                            Height     = Convert.ToInt32(size.Height)
                        });
                    }

                    index++;
                }
            }

            return(list);
        }
Beispiel #13
0
        public Task <ItemUpdateType> FetchAsync(Photo item, IDirectoryService directoryService, CancellationToken cancellationToken)
        {
            item.SetImagePath(ImageType.Primary, item.Path);
            item.SetImagePath(ImageType.Backdrop, item.Path);

            if (item.Path.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || item.Path.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    using (var reader = new ExifReader(item.Path))
                    {
                        double aperture     = 0;
                        double shutterSpeed = 0;

                        DateTime dateTaken;

                        string manufacturer;
                        string model;

                        reader.GetTagValue(ExifTags.FNumber, out aperture);
                        reader.GetTagValue(ExifTags.ExposureTime, out shutterSpeed);
                        reader.GetTagValue(ExifTags.DateTimeOriginal, out dateTaken);

                        reader.GetTagValue(ExifTags.Make, out manufacturer);
                        reader.GetTagValue(ExifTags.Model, out model);

                        if (dateTaken > DateTime.MinValue)
                        {
                            item.DateCreated    = dateTaken;
                            item.PremiereDate   = dateTaken;
                            item.ProductionYear = dateTaken.Year;
                        }

                        var cameraModel = manufacturer ?? string.Empty;
                        cameraModel += " ";
                        cameraModel += model ?? string.Empty;

                        var size        = _imageProcessor.GetImageSize(item.Path);
                        var xResolution = size.Width;
                        var yResolution = size.Height;

                        item.Overview = "Taken " + dateTaken.ToString("F") + "\n" +
                                        (!string.IsNullOrWhiteSpace(cameraModel) ? "With a " + cameraModel : "") +
                                        (aperture > 0 && shutterSpeed > 0 ? " at f" + aperture.ToString(CultureInfo.InvariantCulture) + " and " + PhotoHelper.Dec2Frac(shutterSpeed) + "s" : "") + "\n"
                                        + (xResolution > 0 ? "\n<br/>Resolution: " + xResolution + "x" + yResolution : "");
                    }
                }
                catch (Exception e)
                {
                    _logger.ErrorException("Image Provider - Error reading image tag for {0}", e, item.Path);
                }
            }

            //// Get additional tags from xmp
            //try
            //{
            //    using (var fs = new FileStream(item.Path, FileMode.Open, FileAccess.Read))
            //    {
            //        var bf = BitmapFrame.Create(fs);

            //        if (bf != null)
            //        {
            //            var data = (BitmapMetadata)bf.Metadata;
            //            if (data != null)
            //            {

            //                DateTime dateTaken;
            //                var cameraModel = "";

            //                DateTime.TryParse(data.DateTaken, out dateTaken);
            //                if (dateTaken > DateTime.MinValue) item.DateCreated = dateTaken;
            //                cameraModel = data.CameraModel;

            //                item.PremiereDate = dateTaken;
            //                item.ProductionYear = dateTaken.Year;
            //                item.Overview = "Taken " + dateTaken.ToString("F") + "\n" +
            //                                (cameraModel != "" ? "With a " + cameraModel : "") +
            //                                (aperture > 0 && shutterSpeed > 0 ? " at f" + aperture.ToString(CultureInfo.InvariantCulture) + " and " + PhotoHelper.Dec2Frac(shutterSpeed) + "s" : "") + "\n"
            //                                + (bf.Width > 0 ? "\n<br/>Resolution: " + (int)bf.Width + "x" + (int)bf.Height : "");

            //                var photo = item as Photo;
            //                if (data.Keywords != null) item.Genres = photo.Tags = new List<string>(data.Keywords);
            //                item.Name = !string.IsNullOrWhiteSpace(data.Title) ? data.Title : item.Name;
            //                item.CommunityRating = data.Rating;
            //                if (!string.IsNullOrWhiteSpace(data.Subject)) photo.AddTagline(data.Subject);
            //            }
            //        }

            //    }
            //}
            //catch (NotSupportedException)
            //{
            //    // No problem - move on
            //}
            //catch (Exception e)
            //{
            //    _logger.ErrorException("Error trying to read extended data from {0}", e, item.Path);
            //}

            const ItemUpdateType result = ItemUpdateType.ImageUpdate | ItemUpdateType.MetadataImport;

            return(Task.FromResult(result));
        }