private async Task <ImageResult> ResizeAndUploadImage(IFormFile file, string folderName) { await Task.Delay(0); if (!IsAllowedExtension(file)) { return(ImageResult.Failed(new UploadError { Description = "Only jpg, png, and bmp extensions are allowed." })); } Bitmap originalBMP = new Bitmap(file.OpenReadStream()); double origWidth = originalBMP.Width; double origHeight = originalBMP.Height; double aspectRatio = origWidth / origHeight; if (aspectRatio <= 0) { aspectRatio = 1; } float newHeight = 600; float newWidth = (float)(newHeight * aspectRatio); Bitmap newBMP = new Bitmap(originalBMP, (int)newWidth, (int)newHeight); Graphics graphics = Graphics.FromImage(newBMP); graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight); var uniqueFileName = Guid.NewGuid().ToString("N") + file.FileName; var filePath = Path.Combine(_env.WebRootPath, folderName, uniqueFileName); var folderPath = Path.Combine(_env.WebRootPath, folderName); Directory.CreateDirectory(folderPath); using (var fileStream = new FileStream(filePath, FileMode.Create)) { newBMP.Save(fileStream, GetImageFormat(Path.GetExtension(file.FileName).Substring(1))); } originalBMP.Dispose(); newBMP.Dispose(); graphics.Dispose(); return(ImageResult.Successful(uniqueFileName)); }
/// <summary> /// Deletes an image. /// </summary> /// <param name="oldFileName">Name of the image to be deleted.</param> /// <param name="folderName">Name of the folder where image is in. Default value is 'images'.</param> /// <returns></returns> public async Task <ImageResult> DeleteImage(string oldFileName, string folderName = "images") { await Task.Delay(0); if (string.IsNullOrEmpty(oldFileName)) { return(ImageResult.Failed(new UploadError { Description = "Could not find to file to be delet" })); } string fullPath = Path.Combine(_env.WebRootPath, folderName, oldFileName); if (File.Exists(fullPath)) { File.Delete(fullPath); } return(ImageResult.Successful()); }