1

Im using the following code to fetch image from a file,create an image list by adding all the files from a folder and finally linking it to a listview control to display the thumbnails.The Problem is that if i add 300 Images,the program uses more than 700MB of memory.The image list is taking a lot of memory.Is there any way i can compress/rescale the images at runtime to reduce the memory usage or is there any alternative.

                        this.t.Images.Add(Image.FromFile(f));
                        Filelist.Items.Add(f.ToString());
                        ListViewItem item = new ListViewItem();
                        this.listview.Items.Add(item);
rainbower
  • 141
  • 4
  • 14

1 Answers1

4

Load the image into a temporary, resize it to a new image, and then save the resized image in the list.

using (var tempImage = Image.FromFile(f))
{
    Bitmap bmp = new Bitmap(thumbnailWidth, thumbnailHeight);
    using (Graphics g = Graphics.FromImage(bmp))
    {
        g.DrawImage(tempImage, new Rectangle(0, 0, bmp.Width, bmp.Height);
    }
    t.Images.Add(bmp);
}
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
  • Thanks.The Problem is solved even without resizing by just using the 'using' statement. – rainbower Oct 07 '11 at 08:47
  • @rainbower: the important thing to remember about `Image.FromFile` is the statement in the documentation that says, "The file remains locked until the Image is disposed." Your code not only had a bunch of images, it also had 300 files open. The code above copies the image (in my case, resizing it) and then destroys the original image and closes the file. – Jim Mischel Oct 07 '11 at 14:13