C# WinForm如何将搜索到的最多6张图片合并显示在单个PictureBox中
问题原因
你的现有代码中,每次命中匹配文件时都会直接覆盖PictureBox的Image属性,因此最终只会展示最后一张匹配到的图片。
实现思路
要实现单PictureBox展示最多6张图片,需要先收集所有匹配的图片,再将多张图片拼接为一张完整的位图,最后赋值给PictureBox即可。
完整修改代码
private void bt_Search_Click(object sender, EventArgs e) { try { // 先收集所有匹配的文件路径,最多取6张 var matchedFiles = Directory.GetFiles(FolderPath.SelectedPath) .Where(file => file.Contains(tb1.Text.Trim())) .Take(6) .ToList(); if (matchedFiles.Count == 0) { pictureBox1.Image = null; MessageBox.Show("未找到匹配的图片"); return; } // 定义拼接参数:默认按2行3列布局,可根据需求调整 int imgWidth = 200; // 单张图片显示宽度 int imgHeight = 150; // 单张图片显示高度 int colCount = 3; int rowCount = (int)Math.Ceiling(matchedFiles.Count / (double)colCount); // 创建拼接后的总画布 Bitmap combinedBitmap = new Bitmap(colCount * imgWidth, rowCount * imgHeight); using (Graphics g = Graphics.FromImage(combinedBitmap)) { // 设置高质量渲染参数 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.Clear(Color.White); // 画布背景色可自定义 for (int i = 0; i < matchedFiles.Count; i++) { // 计算当前图片的绘制坐标 int x = (i % colCount) * imgWidth; int y = (i / colCount) * imgHeight; // 加载单张图片并绘制到画布对应位置 using (Bitmap singleImg = new Bitmap(matchedFiles[i])) { g.DrawImage(singleImg, new Rectangle(x, y, imgWidth, imgHeight)); } } } // 释放旧的图片资源,避免内存泄漏 if (pictureBox1.Image != null) { pictureBox1.Image.Dispose(); } // 赋值拼接后的图片 pictureBox1.Image = combinedBitmap; } catch (Exception ex) { // 修正原代码的异常输出错误 MessageBox.Show(ex.ToString()); } }
注意事项
- 可根据需求调整单张图片的宽高、拼接行列数,如需横向排列所有图片可设置列数为6、行数为1
- 建议将
PictureBox的SizeMode属性设置为AutoSize或Zoom,保证拼接后的图片可以完整显示 - 代码中已添加GDI资源释放逻辑,避免长期运行出现内存占用过高的问题
内容的提问来源于stack exchange,提问作者Khang Cao Duy
相关产品推荐
相关产品推荐

