Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
767 views
in Technique[技术] by (71.8m points)

macos - NSImage size not real size with some pictures?

I see that sometimes NSImage size is not real size (with some pictures) and CIImage size is always real. I was testing with this image.

This is source code which I wrote for testing:

NSImage *_imageNSImage = [[NSImage alloc]initWithContentsOfFile:@"<path to image>"];

NSSize _dimensions = [_imageNSImage size];

[_imageNSImage release];

NSLog(@"Width from CIImage: %f",_dimensions.width);
NSLog(@"Height from CIImage: %f",_dimensions.height);




NSURL *_myURL = [NSURL fileURLWithPath:@"<path to image>"];
CIImage *_imageCIImage = [CIImage imageWithContentsOfURL:_myURL];


NSRect _rectFromCIImage = [_imageCIImage extent];

NSLog(@"Width from CIImage: %f",_rectFromCIImage.size.width);
NSLog(@"Height from CIImage: %f",_rectFromCIImage.size.height);

And output is:

enter image description here

So how that can be?? Maybe I'm doing something wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

NSImage size method returns size information that is screen resolution dependent. To get the size represented in the actual file image you need to use an NSImageRep. You can get an NSImageRep from an NSImage using the representations method. Alternatively you can create a NSBitmapImageRep subclass instance directly like this:

NSArray * imageReps = [NSBitmapImageRep imageRepsWithContentsOfFile:@"<path to image>"];

NSInteger width = 0;
NSInteger height = 0;

for (NSImageRep * imageRep in imageReps) {
    if ([imageRep pixelsWide] > width) width = [imageRep pixelsWide];  
    if ([imageRep pixelsHigh] > height) height = [imageRep pixelsHigh];  
}

NSLog(@"Width from NSBitmapImageRep: %f",(CGFloat)width);
NSLog(@"Height from NSBitmapImageRep: %f",(CGFloat)height);

The loop takes into account that some image formats may contain more than a single image (such as TIFFs for example).

You can create an NSImage at this size by using the following:

NSImage * imageNSImage = [[NSImage alloc] initWithSize:NSMakeSize((CGFloat)width, (CGFloat)height)];
[imageNSImage addRepresentations:imageReps];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...