azureasp.net-coreasp.net-core-mvcazure-blob-storageimageresizer

ASP.NET MVC Core Azure Blob Image Resizer


I've got an ASP.NET core application that uploads images to Azure. I am attempting to resize an image using Magick.NET before uploading said image to Azure Blob container. So far, I've managed to save the image to a folder in a local hard drive. Is this the correct way of writing this?

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Product products)
{
    var files = products.UploudThumbnail;

    List<string> image = new List<string>();
    List<string> names = new List<string>();

    if (files != null)
    {
        foreach (var file in files)
        {
            if (ModelState.IsValid)
            {
                if (file.ContentType == "image/jpeg" || file.ContentType == "image/jpg")
                {
                    if (file.Length < 1 * 1000 * 1000) 
                    {
                        var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);

                        var fileName = parsedContentDisposition.FileName.Trim('"');
                        names.Add(fileName);

                        fileName = Guid.NewGuid().ToString() + "-" + fileName;

                        CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);
                        cloudBlockBlob.Properties.ContentType = file.ContentType;
                        await cloudBlockBlob.UploadFromStreamAsync(file.OpenReadStream());

                        image.Add(cloudBlockBlob.Uri.AbsoluteUri);


                        const int size = 20;
                        const int quality = 75;

                        using (var image = new MagickImage(file.OpenReadStream()))
                        {
                            image.Resize(size, size);
                            image.Strip();
                            image.Quality = quality;
                            //how to save it into azure?
                            image.Write(fileName);
                        }

                    }
                    else
                    {
                        ModelState.AddModelError("UploudThumbnail", "Max size not accepted");
                    }
                }
                else
                {
                    ModelState.AddModelError("UploudThumbnail", "jpeg & jpg are accepted");
                }

            }
        }
    }

    _context.Add(products);
    await _context.SaveChangesAsync();
    return RedirectToAction(nameof(Index));
}

Solution

  • Just write the image to a memory stream and upload it using the UploadFromStreamAsync method.

    Example (pseudo):

    using (var memStream = new MemoryStream())
    {
        image.Write(memStream);
    
        memStream.Seek(0, SeekOrigin.Begin);
        await cloudBlockBlob.UploadFromStreamAsync(memStream);
    }