简体   繁体   中英

How to get the image size of an image file in monotouch without loading it?

How to get the image size of an image file in monotouch without loading it in memory?

I tried to use CGImageSource from the MonoTouch.ImageIO namespace, as indicated in the Apple documentation and in this blog post:

oleb.net

But this code doesn't work:

public Size GetImageSizeFromImageFile (string image_file_path)
    {

        CGImageSource imageSource = CGImageSource.FromUrl (NSUrl.FromFilename (image_file_path));

        if (imageSource == null) {
            // Error loading image
            Console.WriteLine ("Error loading image info for file: " + image_file_path);
            return Size.Empty;
        }

        NSDictionary imageProperties = new NSDictionary ();
        imageSource.CopyProperties (imageProperties, 0);

        int width = (int)imageProperties.ValueForKey (new NSString ("kCGImagePropertyPixelWidth"));
        int height = (int)imageProperties.ValueForKey (new NSString ("kCGImagePropertyPixelHeight"));


        Console.WriteLine (@"Image " + image_file_path + " dimensions: " + width + " x " + height+" px");

        imageProperties.Dispose ();

        return new Size(width, height);
    }

Casting to strings doesn't make any difference, the field returns empty.

Any help is appreciated, thanks!

The latest MonoTouch releases makes it a lot easier to get the image properties using the new GetProperties method. Eg

using (var src = CGImageSource.FromUrl (NSUrl.FromFilename (filename))) {
    CGImageOptions options = new CGImageOptions () { ShouldCache = false };
    // do not forget the '0' image index or you won't get what you're looking for!
    using (var p = src.GetProperties (options, 0)) {
        Console.WriteLine ("{0}x{1}", p.PixelWidth, p.PixelHeight);
    }
}

Looks like this is a bug in Mono Touch. I tested the code in XCode with the same image in Mono Touch and it worked in XCode.

In Mono Touch after calling the imageSource.CopyProperties(imageProperties,0) imageProperties.Keys Count is 0

So you should create a bug report at bugzilla.xamarin.com/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM