如何在图像列表中获取图像的实际大小

时间:2017-11-18 18:57:50

标签: c# winforms image-size

我有一段代码,显示特定大小的图片。我希望得到图片的真实尺寸,并希望以真实尺寸显示这些图片。

任何人都可以帮我解决这个问题。 这是我用来获取图片的代码。

private void btnZoom_Click(object sender, EventArgs e)
{
    listView1.Items.Clear();
    imageList1.Images.Clear();

    string[] pics = System.IO.Directory.GetFiles("TestFolder//");
    listView1.View = View.SmallIcon;
    listView1.SmallImageList = imageList1;

    imageList1.ImageSize = new Size(64, 64);
    foreach (string pic in pics)
    {
        imageList1.Images.Add(Image.FromFile(pic));
    }
    for (int j = 0; j < imageList1.Images.Count; j++)
    {
        ListViewItem item = new ListViewItem();

        item.ImageIndex = j;

        listView1.Items.Add(item);
    }
}

它是一个Windows窗体应用程序。

1 个答案:

答案 0 :(得分:0)

以下是另一种方法...使用Tag将Image及其Full Path FileName存储在ListViewItem的Tuple<Image, String>属性中。

类似的东西:

    private void btnZoom_Click(object sender, EventArgs e)
    {
        listView1.Items.Clear();
        imageList1.Images.Clear();

        string[] pics = System.IO.Directory.GetFiles(@"C:\Users\mikes\Pictures\Facebook\Backyard Wildlife"); //"TestFolder//");
        listView1.View = View.SmallIcon;
        listView1.SmallImageList = imageList1;

        imageList1.ImageSize = new Size(64, 64);
        for(int i = 0; i < pics.Length; i++)
        {
            Image img;
            using (FileStream fs = new FileStream(pics[i], FileMode.Open))
            {
                try
                {
                    img = Image.FromStream(fs);
                    imageList1.Images.Add(img);

                    ListViewItem item = new ListViewItem();
                    item.ImageIndex = imageList1.Images.Count - 1;
                    item.Text = System.IO.Path.GetFileNameWithoutExtension(pics[i]);
                    item.Tag = new Tuple<Image, String>(img, pics[i]);
                    listView1.Items.Add(item);
                }
                catch (Exception ex) { }; 
            }


        }
    }

    private void btnView_Click(object sender, EventArgs e)
    {
        if (listView1.SelectedItems.Count > 0)
        {
            ListViewItem item = listView1.SelectedItems[0];
            Tuple<Image, String> data = (Tuple < Image, String >)item.Tag;
            label1.Text = data.Item2;
            pictureBox1.Image = data.Item1;
            Size sz = data.Item1.Size;
            label2.Text = sz.ToString();
        }
    }