开发者

How to check if a C# Bitmap is valid before adding it to a picturebox

开发者 https://www.devze.com 2022-12-18 07:04 出处:网络
How can I check if a C# System.Drawing.Bitmap im开发者_运维技巧age is valid before adding it to a picturebox?It is pretty simple.If you can load the image before you assign it to the picture box then

How can I check if a C# System.Drawing.Bitmap im开发者_运维技巧age is valid before adding it to a picturebox?


It is pretty simple. If you can load the image before you assign it to the picture box then you've sufficiently proven that the image is valid and that the user has something to look at. The GDI+ image decoders very carefully check the file contents. Thus:

    private void button1_Click(object sender, EventArgs e) {
        if (openFileDialog1.ShowDialog(this) != DialogResult.OK) return;
        try {
            Bitmap bmp = new Bitmap(openFileDialog1.FileName);
            if (pictureBox1.Image != null) pictureBox1.Image.Dispose();
            pictureBox1.Image = bmp;
        }
        catch (Exception ex) {
            MessageBox.Show(ex.Message, "Could not load image");
        }
    }


  1. Define "valid"

  2. write a valdation function

  3. call it on the image

  4. if it passes, load the image, otherwise don't


Perhaps you should check this 'RawFormat' property of the 'System.Drawing.Bitmap' class as shown here on MSDN. If the image is empty, that will throw an exception and you can trap it in that case.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号