我想使用 Core Graphics 创建缩略图。缩略图的大小应为 1024 [原文如此],且宽高比与原始图像相同。是否可以直接在 Core Graphics 中设置缩略图所需的大小?
在下面的选项字典中,我可以传递要创建的缩略图的最大尺寸,但是有什么方法可以传递最小尺寸吗?
NSURL * url = [NSURL fileURLWithPath:inPath];
CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)url, NULL);
CGImageRef image=nil;
if (source)
{
NSDictionary* thumbOpts = [NSDictionary dictionaryWithObjectsAndKeys:
(id) kCFBooleanTrue, (id)kCGImageSourceCreateThumbnailWithTransform,
(id)kCFBooleanTrue, (id)kCGImageSourceCreateThumbnailFromImageIfAbsent,
[NSNumber numberWithInt:2048], kCGImageSourceThumbnailMaxPixelSize,
nil];
image = CGImageSourceCreateThumbnailAtIndex(source, 0, (CFDictionaryRef)thumbOpts);
NSLog(@"image width = %d %d", CGImageGetWidth(image), CGImageGetHeight(image));
CFRelease(source);
}
如果您想要尺寸为 1024(最大尺寸)的缩略图,则应该传递 1024,而不是 2048。此外,如果您想确保按照您的规范创建缩略图,您应该要求 kCGImageSourceCreateThumbnailFromImageAlways,而不是 kCGImageSourceCreateThumbnailFromImageIfAbsent,因为后者可能会导致使用现有的缩略图,并且它可能比您想要的要小。
所以,这里的代码可以满足您的要求:
NSURL* url = // whatever;
NSDictionary* d = [NSDictionary dictionaryWithObjectsAndKeys:
(id)kCFBooleanTrue, kCGImageSourceShouldAllowFloat,
(id)kCFBooleanTrue, kCGImageSourceCreateThumbnailWithTransform,
(id)kCFBooleanTrue, kCGImageSourceCreateThumbnailFromImageAlways,
[NSNumber numberWithInt:1024], kCGImageSourceThumbnailMaxPixelSize,
nil];
CGImageSourceRef src = CGImageSourceCreateWithURL((CFURLRef)url, NULL);
CGImageRef imref = CGImageSourceCreateThumbnailAtIndex(src, 0, (CFDictionaryRef)d);
// memory management omitted
Swift 3版本的答案:
func loadImage(at url: URL, maxDimension max: Int) -> UIImage? {
guard let imageSource = CGImageSourceCreateWithURL(url as CFURL, nil)
else {
return nil
}
let options: [CFString: Any] = [
kCGImageSourceShouldAllowFloat: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceThumbnailMaxPixelSize: max
]
guard let thumbnail = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options as CFDictionary)
else {
return nil
}
return UIImage(cgImage: thumbnail)
}