我有pictureBox
直接从互联网上加载图片。图片可以动态更改,并由用户在textBox
内指定TextChanged
事件,该事件会将pictureBox
中的图片更改为textBox
中的网址。当用户单击提交按钮时,图像URL将保存在数据库中。但在保存之前我想验证图像,无论是成功显示图像还是显示错误图像都代替它。那我怎么验证呢?
答案 0 :(得分:2)
您可以使用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的评论,没有使用该链接但是同样的方法来回答这个问题。
答案 1 :(得分:1)
假设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. :)
}
答案 2 :(得分:1)
将下面的代码放在要从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.
}
完成此操作后,您可以将代码放在我显示评论 //放置数据库... 的位置。这可确保文件路径和图像在其他任何内容之前得到验证使用它们。此方法还检查图像文件是否实际上是图像,而不是 .txt 或 .exe ,其扩展名更改为 .jpg 或任何其他图像格式,正如您在评论中提到的,您需要检查路径是否实际指向图像文件。
如果您需要的不仅仅是显示带有错误信息的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.
希望它适合你。