Question

I'm making an application which uses MANY images. The application gets the images from a server, and downloads them one at a time. After many images the creation of a bitmap returns an exception, but i don't know how to solve this. Here is my function for downloading the images:

 public static Bitmap getImageFromWholeURL(String sURL)
    {

        HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(sURL);
        myRequest.Method = "GET";


        // If it does not exist anything on the url, then return null
        try
        {
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(myResponse.GetResponseStream());
            myResponse.Close();
            return bmp;
        }
        catch (Exception e)
        {
            return null;
        }

      }

Can anyone help me out here? Thanks in advance!

Was it helpful?

Solution

"Many images" is of course closely associated with running out of memory. Bitmaps can get large, they'll eat up a lot of unmanaged virtual memory. You'll have to make your program smarter and store less bitmaps in memory. Or save them temporarily to a file. Or re-download them if necessary. And properly clean up their resources with the Dispose() method, especially important for the Bitmap class.

OTHER TIPS

Stream that response to disk rather than keep it in memory. Then keep around the information about the image you've saved to a temporary place instead of the image itself.

If you're showing these all in a Picturebox (and based on your comments I think you are) then you should Dispose of the old images (this blog entry helps explain it):

if(myPictureBox.Image != null)
{
    myPictureBox.Image.Dispose();
}
myPictureBox.Image = getImageFromWholeURL(url);

As a side note on style, method names are supposed to be PascalCase, not camelCase and I'd lose the hungarian notion on the parameter.

What do you do with the System.Drawing.Bitmap objects? Do you keep all of them in memory? Then it is inevitable that you'll get an out of memory exception at some point.

Based on your needs you should discard the images at some point. If you do need them, store them in a file in flash. Also, try using files of smaller sizes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top