[英]How do I dynamically create multiple PictureBox instances from images in folder?
我正在嘗試從包含圖像的文件夾中動態創建圖片框,但是在我的代碼中,我只能創建一個圖片框。 如何為每個圖像創建一個圖片框?
這是我的代碼:
namespace LoadImagesFromFolder
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] images = Directory.GetFiles(@"C:\Users\Public\Pictures\Sample Pictures", "*.jpg");
foreach (string image in images)
{
pictureBox1.Image = new Bitmap(image);
}
}
}
}
您只是為單個PictureBox( pictureBox1
)重寫了圖像值,但是您需要為每張圖片創建一個新的PictureBox並設置其值。 這樣做,你會沒事的。
這樣的事情(僅作為示例,請根據您的需要進行修改!)
foreach (string image in images)
{
PictureBox picture = new PictureBox();
picture.Image = new Bitmap(image);
someParentControl.Controls.Add(picture);
}
您必須使用對話框來選擇文件,在foreach
循環中動態創建PictureBox
控件,然后將它們添加到窗體(或其他容器控件)的Controls
集合中。
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog d = new OpenFileDialog();
// allow multiple selection
d.Multiselect = true;
// filter the desired file types
d.Filter = "JPG |*.jpg|PNG|*.png|BMP|*.bmp";
// show the dialog and check if the selection was made
if (d.ShowDialog() == DialogResult.OK)
{
foreach (string image in d.FileNames)
{
// create a new control
PictureBox pb = new PictureBox();
// assign the image
pb.Image = new Bitmap(image);
// stretch the image
pb.SizeMode = PictureBoxSizeMode.StretchImage;
// set the size of the picture box
pb.Height = pb.Image.Height/10;
pb.Width = pb.Image.Width/10;
// add the control to the container
flowLayoutPanel1.Controls.Add(pb);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.