如何为图像尺寸设置例外?例如,我试图通过openfiledialogue选择一个文件(图像),但如果图像大小小于250x150(假设),我想抛出异常。
public void select_image_button17_Click(object sender, EventArgs e)
{
foreach (Button b in game_panel1.Controls)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "JPG|*.jpg;*.jpeg|PNG|*.png";
// openFileDialog1.InitialDirectory = @"C:\Users\DELL_PC";
if (openFileDialog1.ShowDialog() != DialogResult.OK)
{
break;
}
else
{
string a = openFileDialog1.FileName;
Image ToBeCropped = Image.FromFile(a, true);
ReturnCroppedList(ToBeCropped, 320, 320);
pictureBox1.Image = ToBeCropped;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
AddImagesToButtons(images);
break;
}
}
}
答案 0 :(得分:0)
OpenFileDialog可能只关心在文件系统上选择一个文件。一旦您选择了,您可以自行确认选择是否符合标准,无论该标准是什么。因此,一旦选择,您现在知道该文件的路径,使用图像库加载文件,验证该文件加载没有问题(记住,可能不是一个有效的文件开始),然后验证其维度。如果某些事情没有通过,则采取相应行动,例如:让用户知道文件被拒绝的原因并建议选择一个新文件。
答案 1 :(得分:0)
Windows Exceptions是一个类,当程序收到应用程序执行期间发生的错误时,用于程序收到异常行为的时候,例如,这将使程序成为&# 39;崩溃'或停止工作
Exeptions和validations是2个不同但相似的概念
您正在寻找的是验证机制,有很多方法可以这样做:
您可以做的一件事就是将图像强制调整到所需的尺寸,这样可以避免不需要的图像尺寸:
foreach (Button b in game_panel1.Controls)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "JPG|*.jpg;*.jpeg|PNG|*.png";
// openFileDialog1.InitialDirectory = @"C:\Users\DELL_PC";
if (openFileDialog1.ShowDialog() != DialogResult.OK)
{
break;
}
else
{
string a = openFileDialog1.FileName;
Image ToBeCropped = Image.FromFile(a, true);
ReturnCroppedList(ToBeCropped, 320, 320);
pictureBox1.Image = ToBeCropped;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Size = new Size(210, 110);///--add here your desired size
AddImagesToButtons(images);
break;
}
}
}
但如果您坚持显示错误,则可以使用消息框,进行循环,当满足所需大小时退出循环,否则向用户显示消息Box:
foreach (Button b in game_panel1.Controls)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "JPG|*.jpg;*.jpeg|PNG|*.png";
// openFileDialog1.InitialDirectory = @"C:\Users\DELL_PC";
if (openFileDialog1.ShowDialog() != DialogResult.OK)
{
break;
}
else
{
bool correctSize=false;
var imageH=null;
var imageW=null
while(!correctSize) //make a loop so only desired size will be taken
{
string a = openFileDialog1.FileName;
Image ToBeCropped = Image.FromFile(a, true);
*ReturnCroppedList(ToBeCropped, 320, 320);
pictureBox1.Image = ToBeCropped;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
if(PictureBox1.Image.Size.Width==yourWidth && PictureBox1.Image.Size.height==yourHeight) //Validate size
{ correctSize =true;
AddImagesToButtons(images);
break;
}
else
MessageBox.Show("Please enter image size your desired size ")
}
}
}