CGImage:创建所需大小的缩略图
我想使用 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);
}
I want to create a thumbnail image using Core Graphics. The thumbnail should be size 1024 [sic] with the same aspect ratio as the original image. Is it possible to set the desired size for the thumbnail directly in Core Graphics?
In the options dictionary below, I can pass the max size of the thumbnail to be created, but is there any way to pass a minimum size?
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想要尺寸为 1024(最大尺寸)的缩略图,则应该传递 1024,而不是 2048。此外,如果您想确保按照您的规范创建缩略图,您应该要求 kCGImageSourceCreateThumbnailFromImageAlways,而不是 kCGImageSourceCreateThumbnailFromImageIfAbsent,因为后者可能会导致使用现有的缩略图,并且它可能比您想要的要小。
所以,这里的代码可以满足您的要求:
If you want a thumbnail with size 1024 (maximum dimension), you should be passing 1024, not 2048. Also, if you want to make sure the thumbnail is created to your specifications, you should be asking for kCGImageSourceCreateThumbnailFromImageAlways, not kCGImageSourceCreateThumbnailFromImageIfAbsent, since the latter might cause an existing thumbnail to be used, and it could be smaller than you want.
So, here's code that does what you ask:
Swift 3 版本的答案:
Swift 3 version of the answer: