public async Task <Uri> GetCroppedUri(Guid name, int withSize, int heightSize, Stream originalStream = null) { var nameInStorage = GetNameInStorage(name, Tipo.cropped, withSize, heightSize); if (originalStream == null) { if (_linkCache.Cache.ContainsKey(nameInStorage)) { return(_linkCache.Cache[nameInStorage]); } if (await _azureBlobStorage.ExistsAsync(nameInStorage)) { var uri = GetTrueUri(nameInStorage); _linkCache.Cache.Add(nameInStorage, uri); return(uri); } var originalNameInStorge = GetNameInStorage(name, Tipo.original, 0, 0);//obtem a uri da imagem original para gerar a cropped if (!await _azureBlobStorage.ExistsAsync(originalNameInStorge)) { await _notifications.Handle(new DomainNotification("Id", "Imagem não localizada"), new System.Threading.CancellationToken()); return(GetErroUri()); } originalStream = await _azureBlobStorage.GetStreamAsync(originalNameInStorge); } originalStream.Seek(0, SeekOrigin.Begin); using (Image <Rgba32> image = SixLabors.ImageSharp.Image.Load(originalStream)) { //verifica se da pra fazer o crop if (withSize < image.Width && heightSize < image.Height) { Image <Rgba32> result = image.Clone(ctx => ctx.Resize( new ResizeOptions { Size = new Size(withSize, heightSize), Mode = ResizeMode.Crop })); var resultStream = new MemoryStream(); result.SaveAsPng(resultStream); await _azureBlobStorage.UploadAsync(nameInStorage, resultStream); var uri = GetTrueUri(nameInStorage); _linkCache.Cache.Add(nameInStorage, uri); return(uri); } else // se não der pra fazer pega dimensões abaixo das solicitadas { double fator = 1; fator = withSize - image.Width > heightSize - image.Height ? (double)image.Width / (double)withSize : (double)image.Height / (double)heightSize; var novoWidth = (int)Math.Floor(withSize * fator); if (dimensoes.Where(q => q < novoWidth).Any()) { novoWidth = dimensoes.Where(q => q < novoWidth).Max(); } var novoHeight = (int)Math.Round(((double)novoWidth / (double)withSize) * heightSize); // para manter a proporção solicitada if (novoWidth != image.Width && novoHeight != image.Height) { var novoUri = await GetCroppedUri(name, novoWidth, novoHeight); _linkCache.Cache.Add(nameInStorage, novoUri); return(novoUri); } //retorna o original se estiver menor q o solicitado e nas proporsoes solicitadas var originalNameInStorge = GetNameInStorage(name, Tipo.original, 0, 0);//obtem a uri da imagem original para gerar a cropped var uri = GetTrueUri(originalNameInStorge); _linkCache.Cache.Add(nameInStorage, uri); return(uri); } } }