首页 > 解决方案 > 从文件夹加载未定义的图像

问题描述

我看到了许多类似的线程,但没有任何东西可以帮助我解决我的问题。我是 c# 的新手,我想将 3 个图像从表单上的 3 个不同文件夹加载到 3 个图片框中,然后再打印。图像由第三方应用程序通过屏幕截图创建并保存在这些文件夹中。尽管如此,我无法定义他们的名字,这会导致文件路径出现问题,我认为......我没有创建 SystemWatchFolder,而是看到有人在使用: open.Filter = "Image Files (*.png)|*.png" 这是一般工作还是我需要一个监视文件夹?

我尝试结合来自类似项目的代码并最终得到下面的代码(顺便说一句,抱歉发布了整个代码)。我还尝试将路径更改为: (@"C:....) 相同的错误消息。

我真的需要并感谢您的帮助、评论、想法等。

public Form1()
{
    InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
    Bitmap bmp = new Bitmap("C:\\Users\\Public\\1-2d27a482-b755\\Files\\Snapshots\\Snapshot2\\");
    OpenFileDialog open = new OpenFileDialog();
    open.Filter = "Image Files (*.png)|*.png";

    pictureBox1.Image = bmp;

}
private void PictureBox1_Click(object sender, EventArgs e)
{

    Bitmap bmp = new Bitmap("C:\\Users\\Public\\1-2d27a482-b755\\Files\\Snapshots\\Snapshot2\\");
    OpenFileDialog open = new OpenFileDialog();
    open.Filter = "Image Files (*.png)|*.png";

    pictureBox2.Image = bmp;

}

private void PictureBox2_Click(object sender, EventArgs e)
{
    Bitmap bmp = new Bitmap("C:\\Users\\Public\\1-2d27a482-b755\\Files\\Snapshots\\Snapshot3\\");
    OpenFileDialog open = new OpenFileDialog();
    open.Filter = "Image Files (*.png)|*.png";

    pictureBox3.Image = bmp;

}
private void PictureBox3_Click(object sender, EventArgs e)

框中的图像未显示,我收到此错误:

System.ArgumentException:“参数无效。”

对于这一行: Bitmap bmp = new Bitmap("C:\\Users\\Public\\1-2d27a482-b755\\Files\\Snapshots\\Snapshot1\\");

标签: c#windowsformspngimage-gallery

解决方案


你在做什么错

首先,您Bitmap应该采取路径到您的图片。所以它必须在用户选择图片后在最后初始化OpenFileDialog。此外,您从未打开过您的OpenFileDialog.

所以你所有的方法应该看起来像这样:

private void PictureBox1_Click(object sender, EventArgs e)
{
    OpenFileDialog open = new OpenFileDialog();
    open.Filter = "Image Files (*.png)|*.png|All files (*.*)|*.*";
    if (open.ShowDialog() == DialogResult.OK)
    {
        Bitmap bmp = new Bitmap(open.FileName);
        pictureBox1.Image = bmp;
    }
}

更好的方法来做到这一点

你真的不需要创建三个类似的方法来做同样的事情。您只能创建一个并在所有图片框中使用它:

private void PictureBox_Click(object sender, EventArgs e)
{
    OpenFileDialog open = new OpenFileDialog();
    open.Filter = "Image Files (*.png)|*.png|All files (*.*)|*.*";
    if (open.ShowDialog() == DialogResult.OK)
    {
        Bitmap bmp = new Bitmap(open.FileName);
        PictureBox targetPictureBox = e.Source as PictureBox;
        targetPictureBox.Image = bmp;
    }
}

推荐阅读