c# - 从文件夹加载未定义的图像
问题描述
我看到了许多类似的线程,但没有任何东西可以帮助我解决我的问题。我是 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\\");
解决方案
你在做什么错
首先,您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;
}
}
推荐阅读
- python - Python求和高阶函数
- javascript - 在第二行 Javascript 之后截断段落
- php - 如何使用 slim 框架分隔不同目录中的不同路由
- c# - Application.Current 在发布模式下为空
- google-cloud-platform - 从 Google Translate API 获取多种变体
- qt - Qt平台使用ffmpeg解码时,是否有任何控制属性来解决视频播放速度问题?
- python-3.x - 寻求有关如何开始我的第一个编程项目的帮助
- php - PHP 正则表达式获取所有作为 HTML 元素属性值的电子邮件地址,例如“
我有这个正则表达式模式
/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i
,用于从字符串中获取电子邮件地址。但现在我只想获取所有电子邮件地址,它们是任意 HTML 元素属性的值,包括属性本身。看看我的例子,一切都应该清楚:<?
- laravel - 在开发机器上运行的 Laravel 项目在 Windows 更新后出现“此站点不安全错误”后出现此错误
- python - 重新采样(非采样)在 Pandas 数据帧上产生不可预测的错误