Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone!
I've created a new class derived from PictureBox to save heap memory
cause when using PictureBox.Image or PictureBox.ImageLocation properties
it loads the images into heap memory and the Working Set sometimes jumps
even to 120 MB (when navigating among pictures and creating new Bitmap
objects)

Instead I draw the images directly at the PictureBox.ClientRectangle surface using Graphics class

Code:

public  class EnhancedPictureBox: PictureBox
{

  public EnhancedPictureBox()
  {
     this.Image = null;
     // --- I don't use Image property ---
  }

  // --- path to an image file to draw ---
  private string path = null;

  public string PathToDraw
  {
     get { return this.path; }
     set
     { 
        this.path = value;
        if (PathToDraw != null)
           Draw(); // --- if an image exists ---
     }
  }

  private void Draw()
  {
     using(Stream stream = new FileStream(PathToDraw, FileMode.Open))
     {
        using(Image image = Image.FromStream(stream))
        {
           using( Graphics grfx = this.CreateGraphics())
           {
              grfx.DrawImage(image, 0,0, this.Width, this.Height);
           }
        }
     }
  }

  protected override void OnPaint(PaintEventArgs e)
  {
     Draw();
  }
}

Now my program eats only 30 MB!!!!!!!!

I have some questions:
First, is ot effective to use streams when loading files ....
I'm searching for the best solution so my class would not load anything to heap, but read everything from a hard drive ...
I've been searching MSDN and I found that there is
an UnmanagedMemoryStream in System.IO namespace...

How to use it to reference directly to the image on the hard drive with this stream ... It uses some IntPtr pointers... what is that?? I know it operates unmanaged code but the performance is better ...

Is there any specialized image reading streams in .NET Framework????

Please help!

[edit]Code block added to tidy up formatting. OriginalGriff[/edit]
Posted
Updated 4-May-10 8:52am
v2

1 solution

Not sure if it is a vast improvement, but there is an Image.FromFile[^] which removes the need for you to play with the stream at all.

Don't call Draw from your path property - use Invalidate() instead. This will action the Paint event when it's not too busy with other things. Then hand the e.Graphics object to the Draw routine in the Paint event, which saves the overhead of multiple graphics objects.

And when you post code, surround it with <pre>...</pre> blocks (with the "code block" widget) - it preserves the formatting and makes it easier to read.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900