如何检测图片框是否成功显示图像

本文关键字:是否 成功 显示 图像 显示图 何检测 检测 | 更新日期: 2023-09-27 18:30:30

我有一个直接从互联网加载图像的pictureBox。图像可以动态更改,并由用户在具有TextChanged事件textBox中指定,该事件将图像更改为pictureBox textBox中的 URL。当用户单击提交按钮时,图像 URL 将保存在数据库中。但在保存之前,我想验证图像,无论是成功显示图像还是显示错误图像代替它。那么我该如何验证呢?

如何检测图片框是否成功显示图像

您可以使用 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的评论,没有使用该链接,但与回答此问题的方式相同。

将下面的代码放在从文本框中检索图像路径的函数中,请务必在该路径上执行任何其他操作之前放置它;

    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.
    }

完成此操作后,您可以将代码放在我显示注释的位置//放置您的数据库....此方法还会检查图像文件是否实际上是图像,而不是扩展名更改为.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.

希望它对你有用。

假设 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. :)
        }