So I have a source bitmap that is fairly large, so I shrink it down by a scale of %25 to speed things along in image processing and what not. At the end, I have a group of Rectangles (around 2000) that correspond to sections of the scaled image. I am trying to rescale the Rectangles to match the same areas on the source, then saving that area as a cropped image.
This was my initial code that saved cropped images of the scaled image:
for (int i = 0; i < cells.Count; i++)
{
for (int j = 0; j < cells[i].Count; j++)
{
Cell cell = cells[i][j];
if (cell.width < 0 || cell.height < 0)
{
return;
}
Bitmap bitmap = new Bitmap(cell.width, cell.height);
using (Graphics c = Graphics.FromImage(bitmap))
{
c.DrawImage(inputBitmap, new Rectangle(0, 0, cell.width, cell.height), new Rectangle(cell.x1, cell.y1, cell.width, cell.height), GraphicsUnit.Pixel);
}
bitmap.Save(cellDirectory + "\\cell" + i.ToString("D2") + j.ToString("D2") + ".png", ImageFormat.Png);
}
}
This is my code changed to save the cropped image of the original bitmap:
for (int i = 0; i < cells.Count; i++)
{
for (int j = 0; j < cells[i].Count; j++)
{
Cell cell = cells[i][j];
if (cell.width < 0 || cell.height < 0)
{
return;
}
int x = cell.x1 * 4;
int y = cell.y1 * 4;
int width = cell.width * 4;
int height = cell.height * 4;
Bitmap bitmap = new Bitmap(width, height);
using (Graphics c = Graphics.FromImage(bitmap))
{
c.DrawImage(input, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
}
bitmap.Save(cellDirectory + "\\cell" + i.ToString("D2") + j.ToString("D2") + ".png", ImageFormat.Png);
}
}
The program with the first code finishes in about 20 seconds on average, but for some reason the second version takes over 6 minutes. My brain math might be lying to me, but that seems to be a disproportionate time increase.
The debugging that I have done so far has revealed to me that this line:
c.DrawImage(input, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
is taking longer to complete over time. I suspect that some sort of memory leak could be causing this, but I have tried manually calling Dispose on every object I can and nothing helped. Is there some kind of under-the-hood thing that I should be aware of that is causing this?
Your original method saves a file at the original resolution, while the new method increases both width and height by a factor of 4, which is a 16x increase in the image size. The time difference (6 minutes vs 20 seconds) is roughly proportional: