我想使用CG创建缩略图。它会创建缩略图。
这里我希望缩略图的大小为1024(纵横比)。是否可以直接从CG获得所需大小的缩略图?
在选项字典中,我可以传递可以创建的最大尺寸,但有没有办法让最小尺寸相同..?
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);
}
答案 0 :(得分:19)
如果你想要一个大小为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
答案 1 :(得分:2)
Swift 3 版本的答案:
func loadImage(at url: URL, maxDimension max: Int) -> UIImage? {
guard let imageSource = CGImageSourceCreateWithURL(url as CFURL, nil)
else {
return nil
}
let options = [
kCGImageSourceShouldAllowFloat as String: true as NSNumber,
kCGImageSourceCreateThumbnailWithTransform as String: true as NSNumber,
kCGImageSourceCreateThumbnailFromImageAlways as String: true as NSNumber,
kCGImageSourceThumbnailMaxPixelSize as String: max as NSNumber
] as CFDictionary
guard let thumbnail = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options)
else {
return nil
}
return UIImage(cgImage: thumbnail)
}