How to get the image dimension from the file name

走远了吗. 提交于 2019-12-17 18:33:55

问题


I have a file called FPN = "c:\ggs\ggs Access\images\members\1.jpg "

I'm trying to get the dimension of image 1.jpg, and I'd like to check whether image dimension is valid or not before loading, and if either width or height of the image is less than or equal to zero, pop up a message like "image not in correct format"

Can anyone help me please?


回答1:


System.Drawing.Image img = System.Drawing.Image.FromFile(@"c:\ggs\ggs Access\images\members\1.jpg");
MessageBox.Show("Width: " + img.Width + ", Height: " + img.Height);



回答2:


Wpf class System.Windows.Media.Imaging.BitmapDecoder doesn't read whole file, just metadata.

using(var imageStream = File.OpenRead("file"))
{
    var decoder = BitmapDecoder.Create(imageStream, BitmapCreateOptions.IgnoreColorProfile,
        BitmapCacheOption.Default);
    var height = decoder.Frames[0].PixelHeight;
    var width = decoder.Frames[0].PixelWidth;
}

Update 2019-07-07

If I remember correctly, few months later I found out that dealing with exif'ed images is a little bit more complicated. For some reasons iphones save rotated image instead of normal and they set "rotate this image before displaying" exif flag.
Also turned out that gif is pretty complicated format. It is possible that no frame has full gif size, you have to aggregate it from offsets and frames sizes.

So I used ImageProcessor instead, which dealed with all the problems for me. Never checked if it reads the whole file tho, because some browsers has no exif support and I had to save rotated version anyway.

using (var imageFactory = new ImageFactory())
{
    imageFactory
        .Load(stream)
        .AutoRotate(); //takes care of ex-if
    var height = imageFactory.Image.Height,
    var width = imageFactory.Image.Width
}


来源:https://stackoverflow.com/questions/6455979/how-to-get-the-image-dimension-from-the-file-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!