I'm currently uploading a list of images to azure blob storage via the below function (path is then stored in DB).
This is all working fine however if the images are larger than a certain resolution, I want to resize to hopefully cut down the image file size (this would obviously be.
I've found examples of cropping an 'Image' however as this is a list of IFormFile (from an input type=upload) it doesn't seem to work the same. I've tried converting the IFormFile to an image and then resizing the image, however I'm then unable to convert back to IFormFile.
Any help or pointers would be great. Thanks.
public async Task UploadImagesAsync(IFormFileCollection files, int VehicleID)
{
var connectionString = _configuration.GetConnectionString("AzureStorageAccount");
var container = _uploadService.GetBlobContainer(connectionString);
foreach (var file in files)
{
// Resize file here
// parse the content disposition header
var contentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
// grab file name
var fileName = "Vehicles/" + VehicleID + "/" + contentDisposition.FileName.Trim('"');
// get reference
var blockBlob = container.GetBlockBlobReference(fileName);
// upload
await blockBlob.UploadFromStreamAsync(file.OpenReadStream());
According to my research, we can use SixLabors to resize the image in the application. For example
public async Task UploadImagesAsync(IFormFileCollection files, int VehicleID)
{
foreach (var file in files)
{
var extension = Path.GetExtension(file.FileName);
var encoder = GetEncoder(extension);
if (encoder != null)
{
using (var output = new MemoryStream())
using (Image<Rgba32> image = Image.Load(input))
{
var divisor = image.Width / thumbnailWidth;
var height = Convert.ToInt32(Math.Round((decimal)(image.Height / divisor)));
image.Mutate(x => x.Resize(thumbnailWidth, height));
image.Save(output, encoder);
output.Position = 0;
await blockBlob.UploadFromStreamAsync(output);
}
}
}
}
private static IImageEncoder GetEncoder(string extension)
{
IImageEncoder encoder = null;
extension = extension.Replace(".", "");
var isSupported = Regex.IsMatch(extension, "gif|png|jpe?g", RegexOptions.IgnoreCase);
if (isSupported)
{
switch (extension)
{
case "png":
encoder = new PngEncoder();
break;
case "jpg":
encoder = new JpegEncoder();
break;
case "jpeg":
encoder = new JpegEncoder();
break;
case "gif":
encoder = new GifEncoder();
break;
default:
break;
}
}