首页 > 解决方案 > 如何在flowLayoutPanel中获取动态图片框的图像

问题描述

这就是我打开多张图片并设置为 flowLyaoutPanel 的方式

DialogResult dr = this.openFileDialog.ShowDialog();
        if (dr == System.Windows.Forms.DialogResult.OK)
        {
            // Read the files
            foreach (String file in openFileDialog.FileNames)
            {
                // Create a PictureBox.
                try
                {
                    PictureBox pb = new PictureBox();
                    Image loadedImage = Image.FromFile(file);
                    pb.Height = loadedImage.Height;
                    pb.Width = loadedImage.Width;
                    pb.Image = loadedImage;
                    flowLayoutPanel1.Controls.Add(pb);
                }
                catch (SecurityException ex)
                {

                    MessageBox.Show("Security error. Please contact your administrator for details.\n\n" +
                        "Error message: " + ex.Message + "\n\n" +
                        "Details (send to Support):\n\n" + ex.StackTrace
                    );
                }
                catch (Exception ex)
                {

                    MessageBox.Show("Cannot display the image: " + file.Substring(file.LastIndexOf('\\'))
                        + ". You may not have permission to read the file, or " +
                        "it may be corrupt.\n\nReported error: " + ex.Message);
                }
            }
        }

这就是我卡住的地方,我需要通过使用循环来获取每个图片框中的图像

foreach (Control ctrl in flowLayoutPanel1.Controls) {
            if (ctrl is PictureBox) {

                //problem goes here
                Image img = (PictureBox)ctrl.Image;

                byte[] arr;
                ImageConverter converter = new ImageConverter();
                arr = (byte[])converter.ConvertTo(img, typeof(byte[]));
            }
        }

有没有办法将控件投射到图片框?

标签: c#

解决方案


用于OfType<T>按类型过滤集合。

using System.Linq;
...
foreach (PictureBox pictureBox in flowLayoutPanel1.Controls.OfType<PictureBox>())
{
    Image img = pictureBox.Image;

    byte[] arr;
    ImageConverter converter = new ImageConverter();
    arr = (byte[])converter.ConvertTo(img, typeof(byte[]));        
}

推荐阅读