import <ImageIO/ImageIO.h>
/**
从Image Sources中获取缩略图
@param imageSize 缩略图的大小
*/
- (void)getThumbnailImageFromImageSourceWithSize:(int)imageSize {
CGImageRef thumbImage;
CGImageSourceRef imageSource;
CFDictionaryRef imageOption;
CFStringRef imageKeys[3];
CFTypeRef imageValues[3];
//缩略图尺寸
CFNumberRef thumbSize;
imageSource = CGImageSourceCreateWithURL((CFURLRef)imageFileURL, NULL);
if (imageSource == nil) {
return;
}
//创建缩略图等比缩放大小,会根据长宽值比较大的作为imageSize进行缩放
thumbSize = CFNumberCreate(NULL, kCFNumberIntType, &imageSize);
imageKeys[0] = kCGImageSourceCreateThumbnailWithTransform;
imageValues[0] = (CFTypeRef)kCFBooleanTrue;
imageKeys[1] = kCGImageSourceCreateThumbnailFromImageIfAbsent;
imageValues[1] = (CFTypeRef)kCFBooleanTrue;
//缩放键值对
imageKeys[2] = kCGImageSourceThumbnailMaxPixelSize;
imageValues[2] = (CFTypeRef)thumbSize;
imageOption = CFDictionaryCreate(NULL, (const void **) imageKeys,
(const void **) imageValues, 3,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
//获取缩略图
thumbImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, imageOption);
CFRelease(imageOption);
CFRelease(imageSource);
CFRelease(thumbSize);
//显示缩略图
UIImage *imageResult = [UIImage imageWithCGImage:thumbImage];
UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 300, 320, 200)];
[self.view addSubview:imageView];
imageView.image = imageResult;
//将缩略图保存到本地,查看大小,目的查看缩略图的大小
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *imagePath=[[paths lastObject] stringByAppendingFormat:@"/test_thumb.jpg"];
[UIImageJPEGRepresentation(imageResult, 1) writeToFile:imagePath atomically:YES];
NSLog(@"imagePath %@",imagePath);
}
/**
从Image Sources中创建一个图像
@param imageFileURL 图片的本地路径
*/
- (void)getImageFromImageSource:(NSString *)imageFileURL {
CGImageRef cgimage;
CGImageSourceRef imageSource;
CFDictionaryRef imageOptions;
//键值对,为创建 CFDictionaryRef 做准备
CFStringRef imageKeys[2];
CFTypeRef imageValues[2];
//缓存
imageKeys[0] = kCGImageSourceShouldCache;
imageValues[0] = (CFTypeRef)kCFBooleanTrue;
//float-point
imageKeys[1] = kCGImageSourceShouldAllowFloat;
imageValues[1] = (CFTypeRef)kCFBooleanTrue;
//设置参数,为创建 CGImageSourceRef 对象做准备
imageOptions = CFDictionaryCreate(NULL, (const void **)imageKeys, (const void **)imageValues, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
//创建 CGImageSourceRef 对象,URL为图片的本地路径,imageOptions 为参数的设置
imageSource = CGImageSourceCreateWithURL((CFURLRef)imageFileURL, (CFDictionaryRef)imageOptions);
if (imageSource == nil) {
return;
}
//从 CGImageSourceRef 中获取 CGImageRef 对象
cgimage = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
CFRelease(imageOptions);
CFRelease(imageSource);
//从 CGImageRef 中获取 UIImage 对象
UIImage *imageResult=[UIImage imageWithCGImage:cgimage];
UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 20, 320, 200)];
[self.view addSubview:imageView];
imageView.image = imageResult;
}