c# - 如何在代码中将图像文件添加到图像列表?

标签 c# .net vb.net imagelist

我有一个图像列表,我想在我的代码中将一个图像目录添加到图像列表中。我该怎么做?当我运行代码时:

'Load all of the items from the imagelist
For Each path As String In Directory.GetFiles("Images\LanguageIcons\")
     imlLanguagesIcons.Images.Add(Image.FromFile(path))
Next

我遇到内存不足异常。目前只有 14 张图片,所以应该没有问题。有什么帮助吗?

最佳答案

image.Dispose() 修复内存不足异常。我使用的详细方法是(尽管对某些人来说有点矫枉过正):

        ImageList galleryList = new ImageList();

        string[] GalleryArray = System.IO.Directory.GetFiles(txtSourceDir.Text);    //create array of files in directory
        galleryList.ImageSize = new Size(96, 64);
        galleryList.ColorDepth = ColorDepth.Depth32Bit;

        for (int i = 0; i < GalleryArray.Length; i++)
        {
            if (GalleryArray[i].Contains(".jpg"))   //test if the file is an image
            {
                var tempImage = Image.FromFile(GalleryArray[i]); //Load the image from directory location
                Bitmap pic = new Bitmap(96, 64);
                using (Graphics g = Graphics.FromImage(pic))
                {
                    g.DrawImage(tempImage, new Rectangle(0, 0, pic.Width, pic.Height)); //redraw smaller image
                }
                galleryList.Images.Add(pic);    //add new image to imageList
                tempImage.Dispose();    //after adding to the list, dispose image out of memory
            }

        }

        lstGallery.View = View.LargeIcon;  
        lstGallery.LargeImageList = galleryList;    //set imageList to listView

        for (int i = 0; i < galleryList.Images.Count; i++)
        {
            ListViewItem item = new ListViewItem();
            item.ImageIndex = i;
            lstGallery.Items.Add(item); //add images in sequential order
        }

关于c# - 如何在代码中将图像文件添加到图像列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3312852/

相关文章:

c# - .Net HTML 编辑器控件

c# - Entity Framework - 如何过滤 EntityCollection 关系

c# - 使用因消息类型而异的处理资源来消费队列的消息

c# - Enumerable.ElementAt<TSource> 有什么意义?

c# - String对象真的是通过引用吗?

vb.net - VB 2010和app.config文件和配置文件已被另一个程序更改

sql - 如何将 2 个表中的信息放入 1 行?

c# - 以编程方式从 wcf 配置文件中的单独服务获取基地址的值

c# - 执行时自动插入ID

C# 全局页面变量