Reputation: 533
I have an OpenFileDialog in my WinForm and I want when to select an image to limit the image's size in 100 Ko and the Dimensions in 350x350.
How can I do that ??
Upvotes: 2
Views: 5538
Reputation: 37808
Try this :
OpenFileDialog fileDialog = new OpenFileDialog
{
// managed GDI+ supports bmp, jpeg, gif, png and tiff.
Filter =
"Image files (*.bmp;*.jpg;*.gif;*.png;*.tiff)|*.bmp;*.jpg;*.gif;*.png;*.tiff|All files (*.*)|*.*",
};
if (fileDialog.ShowDialog() == DialogResult.OK)
{
// Many exceptions could be raised in the following code
try
{
var fileSize = new FileInfo(fileDialog.FileName);
var validFilesize = fileSize.Length <= 1024 * 100; // 100 kilo bytes
var validDimensions = false;
// free the file once we get the dimensions
using (Image image = Image.FromFile(fileDialog.FileName))
{
validDimensions = (image.Width <= 350) && (image.Height <= 350);
}
if (!validDimensions || !validFilesize)
{
MessageBox.Show("Error ! Choose another image");
}
else
{
// do something with the file here
}
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
Upvotes: 0
Reputation: 17176
private bool ValidFile(string filename, long limitInBytes, int limitWidth, int limitHeight)
{
var fileSizeInBytes = new FileInfo(filename).Length;
if(fileSizeInBytes > limitInBytes) return false;
using(var img = new Bitmap(filename))
{
if(img.Width > limitWidth || img.Height > limitHeight) return false;
}
return true;
}
private void selectImgButton_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if(ValidFile(openFileDialog1.FileName, 102400, 350, 350))
{
// Image is valid and U can
// Do something with image
// For example set it to a picture box
pictureBox1.Image = new Bitmap(openFileDialog1.FileName);
}
else
{
MessageBox.Show("Image is invalid");
}
}
}
Upvotes: 4
Reputation: 7082
put this as global variable
int imgSize = 0
private void button1_Click(object sender, EventArgs e)
{
Image imageFile;
OpenFileDialog dlg = new OpenFileDialog();
dlg.Title = "Open Image";
dlg.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
imageFile = Image.FromFile(dlg.FileName);
imgHeight = imageFile.Height;
if (imgHeight > 350)
{
MessageBox.Show("Not 350x350 Image", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
imgPhoto.Image = null;
}
else
{
PictureBox1.Image = new Bitmap(dlg.OpenFile());
}
}
dlg.Dispose();
}
Hope this will help.
Upvotes: 0
Reputation: 14581
It depends on what types of images you need to support. For most common types (bmp, jpg, png), you can easily retrieve image info:
string filename = // get it from OpenFileDialog
if (new FileInfo(filename).Length > SOME_LIMIT)
{
MessageBox.Show("!!!");
}
else
{
Image img = Image.FromFile(filename);
MessageBox.Show(string.Format("{0} x {1}", img.Width, img.Height));
}
If you need more extensive support for many image formats, then I suggest using a library like ImageMagick.NET
Upvotes: 4