如何根据ListBox选中索引加载磁盘中对应图片?
解决方案
1. 定义数据类关联图片与矩形信息
不要只在ListBox里存纯文本,用自定义类同时保存图片路径和矩形参数,直接建立两者的关联:
public class ImageRectRecord { public string ImageFilePath { get; set; } public int RectX { get; set; } public int RectY { get; set; } public int RectWidth { get; set; } public int RectHeight { get; set; } // 重写ToString,让ListBox显示需要的矩形信息 public override string ToString() { return $"矩形位置:({RectX}, {RectY}),尺寸:{RectWidth}×{RectHeight}"; } }
2. 保存图片与记录到ListBox、文本文件
绘制矩形并保存Bitmap后,创建ImageRectRecord实例,添加到ListBox,同时序列化所有记录到文本文件(示例用JSON格式,依赖System.Text.Json):
// 假设savePath是Bitmap保存路径,x/y/width/height是矩形参数 var newRecord = new ImageRectRecord { ImageFilePath = savePath, RectX = x, RectY = y, RectWidth = width, RectHeight = height }; // 添加到ListBox listBox1.Items.Add(newRecord); // 序列化所有记录到文件 var allRecords = listBox1.Items.Cast<ImageRectRecord>().ToList(); string json = JsonSerializer.Serialize(allRecords); File.WriteAllText("rect_records.json", json);
3. ListBox切换时加载对应图片
给ListBox绑定SelectedIndexChanged事件处理逻辑,直接读取选中项的图片路径并加载:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { if (listBox1.SelectedItem is ImageRectRecord selectedRecord) { if (File.Exists(selectedRecord.ImageFilePath)) { // 释放旧图片资源,避免内存泄漏 pictureBox1.Image?.Dispose(); pictureBox1.Image = Image.FromFile(selectedRecord.ImageFilePath); } else { pictureBox1.Image = null; MessageBox.Show("对应的图片文件不存在"); } } }
4. 程序重启时恢复ListBox记录
在窗体Load事件中读取文本文件,反序列化后恢复ListBox的项:
private void Form1_Load(object sender, EventArgs e) { string recordPath = "rect_records.json"; if (File.Exists(recordPath)) { string json = File.ReadAllText(recordPath); var allRecords = JsonSerializer.Deserialize<List<ImageRectRecord>>(json); if (allRecords != null) { foreach (var record in allRecords) { listBox1.Items.Add(record); } } } }
注意:如果使用System.Text.Json需要引用对应NuGet包,也可以替换为Newtonsoft.Json,序列化/反序列化逻辑类似。
内容的提问来源于stack exchange,提问作者jhon last
相关产品推荐
相关产品推荐

