views:

371

answers:

1

I have a WinMobile app which allows the user the snap a photo with the camera, and then use for for various things. The photo can be snapped at 1600x1200, 800x600 or 640x480, but it must always be resized to 400px for the longest size (the other is proportional of course). Here's the code:

private void LoadImage(string path)
{
    Image tmpPhoto = new Bitmap(path);

    // calculate new bitmap size...
    double width = ...
    double height = ...

   // draw new bitmap
   Image photo = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
   using (Graphics g = Graphics.FromImage(photo))
   {
       g.FillRectangle(new SolidBrush(Color.White), new Rectangle(0, 0, photo.Width, photo.Height));
       int srcX = (int)((double)(tmpPhoto.Width - width) / 2d);
       int srcY = (int)((double)(tmpPhoto.Height - height) / 2d);
       g.DrawImage(tmpPhoto, new Rectangle(0, 0, photo.Width, photo.Height), new Rectangle(srcX, srcY, photo.Width, photo.Height), GraphicsUnit.Pixel);
   }
   tmpPhoto.Dispose();
   // save new image and dispose
   photo.Save(Path.Combine(config.TempPath, config.TempPhotoFileName), System.Drawing.Imaging.ImageFormat.Jpeg);
   photo.Dispose();
}

Now the problem is that the app breaks in the photo.Save call, with an OutOfMemoryException. And I don't know why, since I dispose the tempPhoto (with the original photo from the camera) as soon as I can, and I also dispose the Graphics obj. Why does this happen? It seems impossible to me that one can't take a photo with the camera and resize/save it without making it crash :( Should I restor t C++ for such a simple thing? Thanks.

A: 

Have you looked at memory usage with each step to see exactly where you're using the most? You omitted your calculations for width and height, but assuming they are right you would end up with photo requiring 400x300x3 (24bits) == 360k for the bitmap data itself, which is not inordinately large.

My guess is that even though you're calling Dispose, the resources aren't getting rleased, especially if you're calling this method multiple times. The CF behaves in an unexpected way with Bitmaps. I call it a bug. The CF team doesn't.

ctacke
you're right about the size and mem occupation...so, is there any solution? :)
devguy
Did you look at the blogs? The "solution" may be to call GC.Collect manually after the Dispose
ctacke