假设我想找出图像的大小,所以如果用户试图在我的iPad应用程序中加载10,000x10,000像素的图像,我可以用对话框显示它们而不是崩溃.如果我这样做[UIImage imageNamed:]或[UIImage imageWithContentsOfFile:]那将立即将我的潜在大图像加载到内存中.
如果我使用Core Image,请这样说:
CIImage *ciImage = [CIImage imageWithContentsOfURL:[NSURL fileURLWithPath:imgPath]];
Run Code Online (Sandbox Code Playgroud)
然后问我的新CIImage尺寸:
CGSize imgSize = ciImage.extent.size;
Run Code Online (Sandbox Code Playgroud)
是否会将整个图像加载到内存中告诉我这个,或者只是查看文件的元数据以发现图像的大小?
该imageWithContentsOfURL函数将图像加载到内存中,是的.
幸运的是,Apple实现CGImageSource了读取图像元数据而无需将实际像素数据加载到iOS4中的内存中,您可以在此博客文章中阅读有关如何使用它的内容(方便地提供了有关如何获取图像尺寸的代码示例).
编辑:这里粘贴代码示例以防止链接腐烂:
#import <ImageIO/ImageIO.h>
NSURL *imageFileURL = [NSURL fileURLWithPath:...];
CGImageSourceRef imageSource = CGImageSourceCreateWithURL((CFURLRef)imageFileURL, NULL);
if (imageSource == NULL) {
// Error loading image
...
return;
}
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:NO], (NSString *)kCGImageSourceShouldCache,nil];
CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, (CFDictionaryRef)options);
if (imageProperties) {
NSNumber *width = (NSNumber *)CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelWidth);
NSNumber *height = (NSNumber *)CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);
NSLog(@"Image dimensions: %@ x %@ px", width, height);
CFRelease(imageProperties);
}
Run Code Online (Sandbox Code Playgroud)
完整的API参考也可在此处获得.
| 归档时间: |
|
| 查看次数: |
571 次 |
| 最近记录: |