private void ApplyBackgroundColour(GDI.Graphics graphics, BackgroundColour backColour, GDI.Bitmap newGdiImage)
 {
     if (backColour == BackgroundColour.None)
     {
         backColour = BackgroundColour.Parse("White");
     }
     using var brush = new GDI.SolidBrush(backColour.Colour);
     graphics.FillRectangle(brush, 0, 0, newGdiImage.Width, newGdiImage.Height);
 }
        public Image ApplyTransforms(Image image, string newResolution = null, string backgroundColour = null,
                                     string watermarkText = null, string imageType = null)
        {
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }
            if (image.ToGdiImage() == null)
            {
                throw new ArgumentException("image must contain a GDI image object");
            }
            if (!TransformsSupplied(newResolution, backgroundColour, watermarkText, imageType))
            {
                return(image);
            }

            var resolution = ImageResolution.Parse(newResolution);
            var backColour = BackgroundColour.Parse(backgroundColour);
            var imgType    = ImageType.Parse(imageType);

            using var oldImage = image;
            var gdiImage    = oldImage.ToGdiImage();
            var newGdiImage = CreateTransformBitmap(resolution, gdiImage);

            using var graphics = GDI.Graphics.FromImage(newGdiImage);

            ApplyBackgroundColour(graphics, backColour, newGdiImage);

            if (resolution != ImageResolution.None)
            {
                DrawImageAtNewResolution(graphics, resolution, gdiImage);
            }
            else
            {
                DrawImageAtOriginalResolution(graphics, gdiImage);
            }

            if (!string.IsNullOrWhiteSpace(watermarkText))
            {
                AddWatermark(graphics, watermarkText);
            }

            if (imgType == ImageType.None)
            {
                imgType = ImageType.Parse(gdiImage.RawFormat.ToString());
            }
            if (!newGdiImage.RawFormat.Equals(imgType.ImageFormat))
            {
                newGdiImage = SetNewGdiImageFormat(newGdiImage, imgType.ImageFormat);
            }

            return(new Image(image.Name, newGdiImage));
        }