Esempio n. 1
0
        private ImageFormat Add(Guid imageId, string?sizeId, Stream stream, ImageOptions options)
        {
            if (options.ValidateSource != null)
            {
                if (!stream.CanSeek)
                {
                    var oldStream = stream;
                    stream = new MemoryStream();
                    oldStream.CopyTo(stream);
                }

                long startPosition = stream.Position;

                using var validateImage = Image.FromStream(stream, false, false);
                options.ValidateSource.Invoke(validateImage);
                stream.Position = startPosition;
            }

            var image = Image.FromStream(stream);

            try {
                RotateImageByExifOrientationData(image);
                ImageFormat format;

                if (options.ImageEditor != null)
                {
                    var editedImage = options.ImageEditor.ApplyEdits(image);
                    format = GetImageFormat(image, editedImage, options);

                    if (editedImage != null)
                    {
                        image.Dispose();
                        image = editedImage;
                    }
                }
                else
                {
                    format = GetImageFormat(image, null, options);
                }

                var path = GetAbsoluteImagePath(new ImageKey(imageId, format), sizeId);

                var encoderParams = new EncoderParameters(1);
                encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, options.JpegQuality);

CreateDirectory:

                if (string.IsNullOrWhiteSpace(sizeId))
                {
                    path.ParentDirectory.Create();
                }

                try {
                    image.Save(path.PathExport, _jpegEncoder, encoderParams);
                }
                catch (DirectoryNotFoundException) when(string.IsNullOrWhiteSpace(sizeId))
                {
                    goto CreateDirectory; // avoid race condition for directory removal during delete prior to image saving.
                }

                return(format);
            }
            finally {
                image.Dispose();
            }
        }