Memory consumption considerations #1738
-
Hello, First time using ImageSharp and run into some increased memory issues. public byte[] GetImage(string imagePath, int? width = null, int? height = null)
{
try
{
byte[] photoBytes = File.ReadAllBytes(imagePath);
MemoryStream inStream = new MemoryStream(photoBytes, 0, photoBytes.Length, true, true);
MemoryStream outStream = new MemoryStream();
if (width != null && height != null)
{
IImageFormat format;
using (Image image = Image.Load(inStream, out format))
{
if ((int)width > (int)height)
{
image.Mutate(x => x.Resize(new Size { Width = (int)width, Height = 0 }).BackgroundColor(Color.FromRgb(27, 49, 71)));
image.Save(outStream, format);
}
else
{
image.Mutate(x => x.Resize(new Size { Width = 0, Height = (int)height }).BackgroundColor(Color.FromRgb(27, 49, 71)));
image.Save(outStream, format);
}
}
}
else
{
IImageFormat format;
using (Image image = Image.Load(inStream, out format))
{
image.Mutate(x => x.BackgroundColor(Color.FromRgb(27, 49, 71)));
image.Save(outStream, format);
}
}
Array.Clear(photoBytes, 0, photoBytes.Length);
ClearMemoryStream(inStream);
inStream.Dispose();
byte[] result = outStream.ToArray();
ClearMemoryStream(outStream);
outStream.Dispose();
return result;
}
catch (Exception ex)
{
this.Logger.LogError(ex, ex.Message);
throw;
}
finally
{
GC.Collect();
}
} Thanks very much. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
What are your typical image sizes? Why all the
With moderate pooling, If you are working with Jpegs, I also recommend to get the latest packages from our MyGet feed since it includes #1694, which is a major improvement. Our next NuGet release will also include #1730. |
Beta Was this translation helpful? Give feedback.
What are your typical image sizes?
Why all the
MemoryStream
-s and thebyte[]
? You can doImage.Load(filePath)
/Image.Load(fileStream)
as well asimage.Save(filePath, format)
andimage.Save(fileStream, format)
.With moderate pooling,
Image
is more likely to allocate arrays which won't be cleaned up until GC triggers. I recommend to keep the default pooling, and do some stress test of your app on the server. Normally GC should clean th…