How to check if a C# Bitmap is valid before adding it to a picturebox
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");
}
}
Define "valid"
write a valdation function
call it on the image
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.
精彩评论