为什么此代码将 ArtistImage 设置为宽度为 0 高度为 0 的图像?
NSURL *artistImageURL = [NSURL URLWithString:@" http://userserve-ak.last.fm/serve/252/8581581.jpg "];
NSImage *artistImage = [[NSImage alloc] initWithContentsOfURL:artistImageURL];
为什么此代码将 ArtistImage 设置为宽度为 0 高度为 0 的图像?
NSURL *artistImageURL = [NSURL URLWithString:@" http://userserve-ak.last.fm/serve/252/8581581.jpg "];
NSImage *artistImage = [[NSImage alloc] initWithContentsOfURL:artistImageURL];
正如 Ken 所写,这张图片中的 DPI 搞砸了。如果要强制 NSImage 设置真实图像大小(忽略 DPI),请使用http://borkware.com/quickies/one?topic=NSImage中描述的方法:
NSBitmapImageRep *rep = [[image representations] objectAtIndex: 0];
NSSize size = NSMakeSize([rep pixelsWide], [rep pixelsHigh]);
[image setSize: size];
NSImage 确实为我加载了这个,但是那个特定的图像有损坏的元数据。根据exif数据,其分辨率为7.1999997999228071e-06 dpi。
NSImage 尊重文件中的 DPI 信息,因此如果您尝试以自然大小绘制图像,您将得到 2520000070 像素的东西。
或多或少可以保证 .representations 包含 NSImageRep*(当然不总是 NSBitmapImageRep)。为了将来扩展的安全起见,可以编写类似下面的代码。它还考虑了多种表示形式(例如在某些 .icns 和 .tiff 文件中)。
@implementation NSImage (Extension)
- (void) makePixelSized {
NSSize max = NSZeroSize;
for (NSObject* o in self.representations) {
if ([o isKindOfClass: NSImageRep.class]) {
NSImageRep* r = (NSImageRep*)o;
if (r.pixelsWide != NSImageRepMatchesDevice && r.pixelsHigh != NSImageRepMatchesDevice) {
max.width = MAX(max.width, r.pixelsWide);
max.height = MAX(max.height, r.pixelsHigh);
}
}
}
if (max.width > 0 && max.height > 0) {
self.size = max;
}
}
@end
最后我检查了一下,NSImage's
-initWithContentsOfURL:
只适用于文件 URL。您需要先检索 URL,然后使用-initWithData: