我有一个pictureBox
直接从互联网加载图像。图像可以动态更改,并由用户在textBox
具有TextChanged
将图像更改pictureBox
为 URL 中的事件的事件中指定textBox
。当用户单击提交按钮时,图像 URL 将保存在数据库中。但在保存之前,我想验证图像,是图像显示成功还是错误图像代替它显示。那么我该如何验证呢?
3 回答
将下面的代码放在从 textBox 检索图像路径的函数中,确保在对该路径执行任何其他操作之前放置它;
string path = "Path to image";
Bitmap bmp;//To validate the Image.
try
{
bmp = new Bitmap(path);//Create a Bitmap object from the given path.
if (bmp != null)
{
pictureBox1.Load(path);//Display the image to the user.
//Now it's safe to store the image path in the database,
//because we have validated it.
bmp.Dispose();//Dispose the Bitmap object to free occupied resources.
//Place you database related code here which uses the path we just validated.
}
}
catch (ArgumentException)
{
MessageBox.Show("The specified image file is invalid.");
//Show error image in PictureBox.
//(pictureBox1.Image="Path to error image").
//Don't store image path,its invalid.
}
catch (FileNotFoundException)
{
MessageBox.Show("The path to image is invalid.");
//Show error image in PictureBox.
//(pictureBox1.Image="Path to error image").
//Don't store image path,its invalid.
}
完成此操作后,您可以将代码放置在我显示注释的位置//Place your database...。这可确保文件路径和图像在其他任何东西使用它们之前得到验证。`此方法还检查是否图像文件实际上是图像,而不是扩展名为.jpg或任何其他图像格式的.txt或.exe,正如您在评论中提到的,您需要检查路径是否实际指向图像文件。
如果您需要的不仅仅是显示MessageBox
错误信息,您可以扩展异常处理机制。还有一点值得一提的是,before you display any image or do anything you will have to check if the url is valid one,to simplify this step you can try to download the file(it can be anything - an image,an executable,a text file or at least a web page,when it has been downloaded pass the path to that file(relative to filesystem) to this function.
希望对你有效。
您可以使用 LoadComplete 事件来查看它何时发生更改,以及 eventArg 的错误是 null(成功)还是非 null(失败)。
void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
MessageBox.Show(e.Error.ToString());
}
this.pictureBox1.Validated += new EventHandler(pictureBox1_Validated);
this.pictureBox1.ImageLocation = this.textBox1.Text;
- 编辑:刚刚看到 Dips 的评论,没有使用该链接,但回答此问题的方法相同。
假设 Pic1 是您的控件的名称。要进行验证,您可以简单地使用,
if(pic1.ImageLocation.Trim().Length>4) // > 4 since a shortest valid image
file will be a.png or something
similar; length= 5
{
if(validExtensions(pic1.ImageLocation)
{
//then put the path to database
}
}
更新
//Mehod to valid image extensions
private bool validExtensions(string url)
{
var imgs = new []{".jpg",".gif",".png",".bmp",".jpeg"};
var ext = System.IO.Path.GetFileExtention(url); // see the correct method
in intellisense
if(imgs.Contains(ext)
return false;
}
更新 2
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png";
dialog.InitialDirectory = @"C:\";
dialog.Title = "Please select an image file to encrypt.";
if (dialog.ShowDialog() == DialogResult.OK)
{
//Encrypt the selected file. I'll do this later. :)
}