Reputation: 1611
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:
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!
Upvotes: 3
Views: 1430
Reputation: 43553
The latest MonoTouch releases makes it a lot easier to get the image properties using the new GetProperties
method. E.g.
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);
}
}
Upvotes: 4
Reputation: 512
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/
Upvotes: 0