1

I am trying to take a file from an Azure blob, resize it using ImageSharp, and serve it to the client. I have the following code, which works:

    public async Task<IActionResult> GetFile(string url, int width =0, int height=0) {
        // Connect to Azure
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference("images");
        CloudBlockBlob blockBlob = container.GetBlockBlobReference(url);


        var azureStream = new MemoryStream();          
        await blockBlob.DownloadToStreamAsync(azureStream);
        azureStream.Seek(0, SeekOrigin.Begin);

        var image = Image.Load(azureStream);
        image.Mutate(x=>x.Resize(new ResizeOptions(){
            Size = new Size(width, height),
            Mode = ResizeMode.Pad

        }));

        var stream = new MemoryStream();
        image.SaveAsPng(stream);
        stream.Seek(0, SeekOrigin.Begin);
        return File(stream, "image/png");

    }

Is there a more efficient way to do this vs creating 2 memory streams? This will eventually take tons of requests and I really want it to be as performant as possible.

Chris Kooken
  • 32,730
  • 15
  • 85
  • 123
  • Don't think you can get around of having an `input` and `output` stream – NotFound Feb 18 '19 at 15:22
  • 1
    In the ImageSharp.Web project we reduce allocations by using a memorystream backed with pooling. https://github.com/SixLabors/ImageSharp.Web/blob/0ad58bb128778b7eec37a8784686c43486b92318/src/ImageSharp.Web/ChunkedMemoryStream.cs – James South Feb 20 '19 at 23:34

0 Answers0