Jus*_*Boo 27 macos cocoa core-graphics nsimage
我看到有时NSImage大小不是真正的大小(有一些图片)而且CIImage大小总是真实的.我正在测试这个图像.
这是我为测试编写的源代码:
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);
Run Code Online (Sandbox Code Playgroud)
输出是:

那怎么可能?也许我做错了什么?
Dav*_*lis 41
NSImage size方法返回依赖于屏幕分辨率的大小信息.要获得实际文件映像中表示的大小,您需要使用NSImageRep.您可以NSImageRep从NSImage使用该representations方法获得.或者,您可以NSBitmapImageRep像这样直接创建子类实例:
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);
Run Code Online (Sandbox Code Playgroud)
该循环考虑到某些图像格式可能包含多个图像(例如TIFF).
您可以使用以下命令创建此大小的NSImage:
NSImage * imageNSImage = [[NSImage alloc] initWithSize:NSMakeSize((CGFloat)width, (CGFloat)height)];
[imageNSImage addRepresentations:imageReps];
Run Code Online (Sandbox Code Playgroud)
NSImage大小方法以磅为单位返回大小.要获得以像素为单位表示的大小,您需要检查NSImage.representations属性,该属性包含具有pixelWide/pixelHigh属性和简单更改大小NSImage对象的NSImageRep对象数组:
@implementation ViewController {
__weak IBOutlet NSImageView *imageView;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do view setup here.
NSImage *image = [[NSImage alloc] initWithContentsOfFile:@"/Users/username/test.jpg"];
if (image.representations && image.representations.count > 0) {
long lastSquare = 0, curSquare;
NSImageRep *imageRep;
for (imageRep in image.representations) {
curSquare = imageRep.pixelsWide * imageRep.pixelsHigh;
if (curSquare > lastSquare) {
image.size = NSMakeSize(imageRep.pixelsWide, imageRep.pixelsHigh);
lastSquare = curSquare;
}
}
imageView.image = image;
NSLog(@"%.0fx%.0f", image.size.width, image.size.height);
}
}
@end
Run Code Online (Sandbox Code Playgroud)
感谢Zenopolis的原始ObjC代码,这里有一个非常简洁的Swift版本:
func sizeForImageAtURL(url: NSURL) -> CGSize? {
guard let imageReps = NSBitmapImageRep.imageRepsWithContentsOfURL(url) else { return nil }
return imageReps.reduce(CGSize.zero, combine: { (size: CGSize, rep: NSImageRep) -> CGSize in
return CGSize(width: max(size.width, CGFloat(rep.pixelsWide)), height: max(size.height, CGFloat(rep.pixelsHigh)))
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8801 次 |
| 最近记录: |