简体   繁体   English

如何从文件夹中的图像动态创建多个PictureBox实例?

[英]How do I dynamically create multiple PictureBox instances from images in folder?

I'm trying to create pictures boxes dynamically from a folder containing images, but in my code I can only create one picture box. 我正在尝试从包含图像的文件夹中动态创建图片框,但是在我的代码中,我只能创建一个图片框。 How do I do to create one picture box per image? 如何为每个图像创建一个图片框?

Here is my code: 这是我的代码:

 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); 

        }
    }
}
}

You're just rewriting the image value for your single PictureBox ( pictureBox1 ), but you need to create a new PictureBox for every picture instead and set its value. 您只是为单个PictureBox( pictureBox1 )重写了图像值,但是您需要为每张图片创建一个新的PictureBox并设置其值。 Do that and you'll be fine. 这样做,你会没事的。

Something like this (just an example, modify this to your needs!) 这样的事情(仅作为示例,请根据您的需要进行修改!)

foreach (string image in images)
{
   PictureBox picture = new PictureBox();
   picture.Image = new Bitmap(image); 
   someParentControl.Controls.Add(picture);
}

You have to use a dialog to select the files, create the PictureBox controls dynamically in the foreach loop and add them to the form's (or other container control's) Controls collection. 您必须使用对话框来选择文件,在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM