轉載地址:http://www.tanhao.me/pieces/1019.htmlhtml
CGImageSource是對圖像數據讀取任務的抽象,經過它能夠得到圖像對象、縮略圖、圖像的屬性(包括Exif信息)。ide
1.建立CGImageSourceRef測試
1
2
|
NSString *imagePath = [[NSBundle bundleForClass:self.class] pathForImageResource:@"test.png"];
CGImageSourceRef imageSource = CGImageSourceCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:imagePath],NULL);
|
2.獲取圖像spa
1
|
CGImageRef imageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
|
3.建立圖像的縮略圖翻譯
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
//縮略圖的寬和高
double thumbnailWidth=xxx,thumbnailHeight=xxx;
//縮略圖的信息的字典
NSDictionary *thumbnailInfo = @{
(NSString *)kCGImageSourceCreateThumbnailFromImageAlways : @YES,
(NSString *)kCGImageSourceThumbnailMaxPixelSize : [NSNumber numberWithInt:MAX(thumbnailWidth,thumbnailHeight)],
(NSString *)kCGImageSourceCreateThumbnailWithTransform : @YES,
};
//獲得縮略圖
CGImageRef imageRef = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, (__bridge CFDictionaryRef)thumbnailInfo );
|
4.獲取圖像的屬性信息3d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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];
//Exif信息
NSDictionary *exifInfo = (__bridge NSDictionary *)CFDictionaryGetValue(imageInfo, kCGImagePropertyExifAuxDictionary);
|
其中獲取到的kCGImagePropertyPixelHeight和kCGImagePropertyPixelHeight的數值是原始的值,也就是旋轉以前的數值,因此要獲取到顯示圖像的寬和高,須要對應kCGImagePropertyOrientation的值,而經過查看kCGImagePropertyOrientation的文檔介紹,值分別從1-8,但其解釋卻讓人看不懂,通過測試,得出與UIImageOrientation有如下的映射關係:code
UIImageOrientationUp: 1 正常方向(默認值) 如圖:orm
UIImageOrientationDown: 3 旋轉180度(朝左朝右固然是同樣的) 如圖:htm
UIImageOrientationLeft: 8 向左逆時針旋轉90度 如圖:對象
UIImageOrientationRight: 6 向右順時針旋轉90度 如圖:
UIImageOrientationUpMirrored: 2 將原圖水平的翻轉到背面 如圖:
UIImageOrientationDownMirrored: 4 在水平翻轉以後再旋轉180度 如圖:
UIImageOrientationLeftMirrored: 5 在水平翻轉以後向左逆時針旋轉90度 如圖:
UIImageOrientationRightMirrored: 7 在水平翻譯以後向右順時針旋轉90度 如圖:
相關的Demo:頭像裁剪選擇器McAvatarView