我有一个图像列表,我想在我的代码中将一个图像目录添加到图像列表中。我该怎么做?当我运行代码时:
'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/