I'm using asp.net 3.5 and c# on my website. Here is myquestion:
I have an upload button and asp:Image on a page. An user can upload an image from his computer and that image will be displayed in the asp:image. But before I display the image, I would like to check the width and height of the uploaded image. How do I do this?
Image img = System.Drawing.Image.FromFile("test.jpg");
int width = img.Width;
int height = img.Height;
You may need to add the System.Drawing reference.
You may also use the FromStream
function if you have not saved the image to disk yet, but looking at how you're using the image (viewable by user in an Image control), I suspect it's already on disk. Stream to image may or may not be faster than disk to image. You might want to do some profiling to see which has better performance.
In ASP.NET you typically have the byte[] or the Stream when a file is uploaded. Below, I show you one way to do this where bytes is the byte[] of the file uploaded. If you're saving the file fisrt then you have a physical file. and you can use what @Jakob or @Fun Mun Pieng have shown you.
Either ways, be SURE to dispose your Image instance like I've shown here. That's very important (the others have not shown this).
using (Stream memStream = new MemoryStream(bytes))
{
using (Image img = System.Drawing.Image.FromStream(memStream))
{
int width = img.Width;
int height = img.Height;
}
}
Try the following:
public bool ValidateFileDimensions()
{
using(System.Drawing.Image myImage =
System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream))
{
return (myImage.Height == 140 && myImage.Width == 140);
}
}
Load the image into an Image and check the dimensions serverside?
Image uploadedImage = Image.FromFile("uploadedimage.jpg");
// uploadedImage.Width and uploadedImage.Height will have the dimensions...
Try this:
Stream ipStream = fuAttachment.PostedFile.InputStream;
using (var image = System.Drawing.Image.FromStream(ipStream))
{
float w = image.PhysicalDimension.Width;
float h = image.PhysicalDimension.Height;
}
Try this.
public boolean CheckImgDimensions(string imgPath, int ValidWidth , int ValidHeight){
var img = Image.FromFile(Server.MapPath(imgPath));
return (img.width == ValidWidth && img.height == ValidHeight );
}
Use:
if ( CheckImgDimensions("~/Content/img/MyPic.jpg",128,128) ){
/// what u want
}
来源:https://stackoverflow.com/questions/5190069/check-uploaded-images-dimensions