Exemple #1
0
        public void ResizeImage(IFormFile uploadedFile, string desiredThumbPath, int desiredWidth = 0, int desiredHeight = 0)
        {
            string webRoot = _fileHandler.GetRootUrl();

            if (uploadedFile.Length > 0)
            {
                using (var stream = uploadedFile.OpenReadStream())
                {
                    var uploadedImage = System.Drawing.Image.FromStream(stream);

                    //decide how to scale dimensions
                    if (desiredHeight == 0 && desiredWidth > 0)
                    {
                        var img           = uploadedImage.ScaleByWidth(desiredWidth); // returns System.Drawing.Image file
                        var fullPath      = Path.Combine(webRoot, desiredThumbPath);
                        var currentFolder = _fileHandler.GetDirectoryName(fullPath);
                        _fileHandler.CreateDirectory(currentFolder);
                        img.SaveAs(fullPath);
                    }
                    else if (desiredWidth == 0 && desiredHeight > 0)
                    {
                        var img           = uploadedImage.ScaleByHeight(desiredHeight); // returns System.Drawing.Image file
                        var fullPath      = Path.Combine(webRoot, desiredThumbPath);
                        var currentFolder = _fileHandler.GetDirectoryName(fullPath);
                        _fileHandler.CreateDirectory(currentFolder);
                        img.SaveAs(fullPath);
                    }
                    else
                    {
                        var img           = uploadedImage.Scale(desiredWidth, desiredHeight); // returns System.Drawing.Image file
                        var fullPath      = Path.Combine(webRoot, desiredThumbPath);
                        var currentFolder = _fileHandler.GetDirectoryName(fullPath);
                        _fileHandler.CreateDirectory(currentFolder);
                        img.SaveAs(fullPath);
                    }
                }
            }
        }