0

我现在正在制作图像查看器。但是我不知道如何在文件夹中设置文件的编号。我必须设置 CurrentImage 编号。我描述的功能是 Prev 和 Next 按钮。

受保护的 FileInfo[] 图像文件;

受保护的 int pCurrentImage ;

 private void btnFileOpen_Click(object sender, EventArgs e)
    {
        OpenFileDialog dlg = new OpenFileDialog();
        dlg.Filter = "이미지 파일|*.jpg;*.bmp;*.gif;*.png";

        if (dlg.ShowDialog() == DialogResult.OK)
        {
            Bitmap b = new Bitmap(dlg.FileName);
            pictureBox1.Image = (Image)b.Clone();
            pCurrentImage = 0;

            DirectoryInfo di = new DirectoryInfo(dlg.FileName.Replace(dlg.SafeFileName, ""));

            imageFiles = di.GetFiles("*.jpg;*.bmp;*.gif;*.png");

        }
    } 
   private void btnBefore_Click(object sender, EventArgs e)
    {
                    --pCurrentImage;
        if (imageFiles.Length > 0)
        {
            pCurrentImage = pCurrentImage == 0 ? imageFiles.Length - 1 : --pCurrentImage;
            ShowCurrentImage();
        }

    }

    private void ShowCurrentImage()
    {
         if (pCurrentImage >= 0 && pCurrentImage <= imageFiles.Length - 1)
        {
            pictureBox1.Image = Bitmap.FromFile(imageFiles[pCurrentImage].FullName);
            //Invalidate();
            pictureBox1.Invalidate();
        }
    }


    private void btnNext_Click(object sender, EventArgs e)
    {
        ++pCurrentImage;
        if (imageFiles.Length > 0)
        {
            pCurrentImage = pCurrentImage == imageFiles.Length - 1 ? 0 : ++pCurrentImage;
            ShowCurrentImage();
        }
    }
4

1 回答 1

0

尝试使用 filter 调用 GetFiles *.*。GetFiles 将 Directory 中的所有文件返回到 FileInfo[] 数组中。现在您可以使用 LINQ 查询过滤结果:

        FileInfo fi = new FileInfo(dlg.FileName);
        var list = fi.Directory.GetFiles("*.*",SearchOption.TopDirectoryOnly);
        imageFiles = (from FileInfo file in list where (file.Extension == ".jpg" || file.Extension == ".bmp" || file.Extension == ".gif" || file.Extension == ".png") select file).ToArray();

以及如何获得 CurrentImage 编号?

pCurrentImage = imageFiles.ToList().FindIndex(file => file.FullName == dlg.FileName);

并且不记得正确的 btnBefore_Click 和 btnNext_Click 按钮处理:

private void btnBefore_Click(object sender, EventArgs e)
{
    --pCurrentImage;
    if (imageFiles.Length > 0)
    {
        pCurrentImage = pCurrentImage < 0 ? imageFiles.Length - 1 : pCurrentImage;
        ShowCurrentImage();
    }
}       

 private void btnNext_Click(object sender, EventArgs e)
        {
            ++pCurrentImage;
            if (imageFiles.Length > 0)
            {
                pCurrentImage = pCurrentImage >= imageFiles.Length ? 0 : pCurrentImage;
                ShowCurrentImage();
            }
        }
于 2013-05-27T14:05:25.477 回答