I have to import a large amount of image crops off of many images that are all ready stored in my database. I have tried using statements and disposing of my bitmap objects each time. But I am still getting a Memory Overflow Exception that my system is out of memory.
Here is some sample code of what I am doing.
public void CropImage(List<ImageClass> data)
{
foreach (var obj in data)
{
//I have a data base method that returns a data object that
//contains the file bytes of the image id in data: 'file'
//My List<ImageClass> data contains an ID of the original image
//start x,y coords for the upper left corner of the rectangle,
//and the width and height of the rectangle.
Image img = Image.FromStream(new MemoryStream(file.Data));
Bitmap bmp = new Bitmap((Bitmap)img);
Rectangle cropArea = new Rectangle(obj.x_coordinate,
obj.y_coordinate,
obj.width,
obj.height);
Bitmap cropImage = bmp.Clone(cropArea, bmp.PixelFormat);
SaveFile(cropImage, file, obj.scanID);
img.Dispose();
bmp.Dispose();
cropImage.Dispose();
}
}
public void SaveFile(Bitmap cropImage, FileData file, int OCRscanID)
{
EncoderParameters encoderParams = new EncoderParameters();
encoderParams.Param[0] = new EncoderParameter(
System.Drawing.Imaging.Encoder.Quality,
50L);
ImageCodecInfo codecInfo = GetEncoderInfo("image/jpeg");
MemoryStream newImage = new MemoryStream();
cropImage.Save(newImage, codecInfo, encoderParams);
byte[] newData = newImage.ToArray();
//Saving data bytes to database of the cropped image
}
private ImageCodecInfo GetEncoderInfo(string mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for (j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}
I know I can trim up some of the code like searching for an encoder to just use the image/jpeg. But i had another application for this code another project. I just can't seem to get past the memory overflow.
I need to cycle through about 20k images.