Como evitar bitmap sem memória ao trabalhar com imagens muito grandes, por exemplo: 10.000.000 pixels e acima
Atualmente, estou trabalhando em um sistema que carrega uma imagem muito grande, com largura mínima x altura> = 10.000.000 pixels.
Mas a proporção da imagem de upload do usuário geralmente não corresponde à nossa taxa de requisitos, então eu tenho que cortá-la na proporção adequada, mas ao usar o bitmap System.Drawing para cortá-la, sempre tenho a exceção SytemOutOfMemory.
Eu tentei Bitmap.Clone e Graphic.DrawImage com RectangleF correto, mas sem sorte.
Existe alguma maneira de fazer isso sem obter a exceção de exceção de memória ou existem alternativas à biblioteca System.Drawing para executar essa tarefa facilmente?
Meu código para carregar a imagem do arquivo de upload do usuário:
var fileBinary = new byte[stream.Length];
stream.Read(fileBinary, 0, fileBinary.Length);
stream.Position = 0;
var fileExtension = Path.GetExtension(fileName);
using (Image image = Image.FromStream(stream, false, false))
{
//validation and check ratio
CropImage(image, PORTRAIT_RATIO, fileExtension);
}
E a função CropImage:
//Crop Image from center with predefine ratio
private byte[] CropImage(Image sourceImg, float ratio, string fileExtension)
var height = sourceImg.Height;
var width = sourceImg.Width;
var isPortrait = width < height;
RectangleF croppingRec = new RectangleF();
float positionX = 0;
float positionY = 0;
float cropHeight = (float)height;
float cropWidth = cropHeight * PORTRAIT_RATIO;
positionY = 0;
positionX = (width - cropWidth) / 2;
if (cropWidth > width)
{
cropWidth = width;
cropHeight = cropWidth * (1 / PORTRAIT_RATIO);
positionX = 0;
positionY = ((height - cropHeight) / 2);
}
croppingRec.Width = cropWidth;
croppingRec.Height = cropHeight;
croppingRec.X = positionX;
croppingRec.Y = positionY;
Bitmap bmpImage = sourceImg as Bitmap;
Bitmap bmpCrop = bmpImage.Clone(croppingRec, bmpImage.PixelFormat);
bmpCrop.Save("D:/test" + fileExtension, ImageFormat.Jpeg);
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(bmpCrop, typeof(byte[]));
}
}