CGImageSource是对图像数据读取任务的抽象,通过它可以获得图像对象、缩略图、图像的属性(包括Exif信息)。
创建CGImageSourceRef
1 2
| NSString *imagePath = [[NSBundle bundleForClass:self.class] pathForImageResource:@"test.png"]; CGImageSourceRef imageSource = CGImageSourceCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:imagePath],NULL);
|
获取图像
1
| CGImageRef imageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
|
创建图像的缩略图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| double thumbnailWidth=xxx,thumbnailHeight=xxx; if (imageSource != NULL) { NSDictionary *options = @{ (id) kCGImageSourceCreateThumbnailWithTransform : @YES, (id) kCGImageSourceCreateThumbnailFromImageAlways : @YES, (id) kCGImageSourceThumbnailMaxPixelSize : [NSNumber numberWithInt:MAX(thumbnailWidth,thumbnailHeight)] }; CGImageRef thumbnailRef = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, (__bridge CFDictionaryRef)options); CFRelease(imageSource); if (thumbnailRef) { lastImage = [UIImage imageWithCGImage:thumbnailRef]; CGImageRelease(thumbnailRef); } }
|
CFDictionaryRef
字典规范的操作标识:
1 2 3 4 5 6 7
| kCGImageSourceCreateThumbnailFromImageIfAbsent (如果有缩略图则使用,无则使用原图产生缩略图)默认值是kCFBooleanFalse kCGImageSourceCreateThumbnailFromImageAlways (用原图产生缩略图)默认值是kCFBooleanFalse kCGImageSourceThumbnailMaxPixelSize (缩略图长或宽最大尺寸)value为CFNumber类型 kCGImageSourceCreateThumbnailWithTransform (根据exif标记 自动旋转)默认值是kCFBooleanFalse
|
获取图像的属性信息
1 2 3 4 5 6 7 8 9 10 11 12 13
| CFDictionaryRef imageInfo = CGImageSourceCopyPropertiesAtIndex(imageSource, 0,NULL); NSNumber *pixelWidthObj = (__bridge NSNumber *)CFDictionaryGetValue(imageInfo, kCGImagePropertyPixelWidth); NSNumber *pixelHeightObj = (__bridge NSNumber *)CFDictionaryGetValue(imageInfo, kCGImagePropertyPixelHeight); NSInteger orientation = [(__bridge NSNumber *)CFDictionaryGetValue(imageInfo, kCGImagePropertyOrientation) integerValue]; NSDictionary *exifInfo = (__bridge NSDictionary *)CFDictionaryGetValue(imageInfo, kCGImagePropertyExifAuxDictionary);
|
其中获取到的 kCGImagePropertyPixelHeight
和 kCGImagePropertyPixelHeight
的数值是原始的值,也就是旋转之前的数值;
所以要获取到显示图像的宽和高,需要对应 kCGImagePropertyOrientation
的值,值分别从1-8,与UIImageOrientation有以下的映射关系:
- UIImageOrientationUp: 1 正常方向(默认值)
- UIImageOrientationDown: 3 旋转180度(朝左朝右当然是一样的)
- UIImageOrientationLeft: 8 向左逆时针旋转90度
- UIImageOrientationRight: 6 向右顺时针旋转90度
- UIImageOrientationUpMirrored: 2 将原图水平的翻转到背面
- UIImageOrientationDownMirrored: 4 在水平翻转之后再旋转180度
- UIImageOrientationLeftMirrored: 5 在水平翻转之后向左逆时针旋转90度
- UIImageOrientationRightMirrored: 7 在水平翻转之后向右顺时针旋转90度