让NSdata对象转变成UIImage对象再裁剪图片的方法

下面的代码是从自己项目代码里抠出来的,作为自己的笔记,raw文件尚未测试,有问题可以留言。

objectivec 复制代码
- (void)p_cropImg {
    // 1. 获取待裁剪图片. 暂时让方向固定为up
    UIImage *image = [UIImage imageWithData:self.photoData];
    image = kCGImagePropertyOrientationUp;
    
    // 2. 获取待裁剪图片的属性, 复制到cropImg, 才能使得cropImg有属性信息, 否则只有图片画面, 没有曝光三要素数值和摄像头信息等内容
    CGImageSourceRef source = CGImageSourceCreateWithData((CFDataRef)self.photoData, NULL);
    NSDictionary *dict = (__bridge NSDictionary *)CGImageSourceCopyPropertiesAtIndex(source, 0, NULL);
    CFRelease(source);
    
    NSMutableDictionary *cropImgDict = @{}.mutableCopy;
    NSDictionary *exif = dict[(NSString *)kCGImagePropertyExifDictionary];
    cropImgDict[(NSString *)kCGImagePropertyExifDictionary] = exif;
    
    NSDictionary *tiff = dict[(NSString *)kCGImagePropertyTIFFDictionary];
    // 可修改方向, 相册根据该方向值显示图片, 这个值和CGImageSourceCreateWithData的data有关, 不能只旋转UIImage而不修改tiff.
    NSMutableDictionary *cropImgDictTiff = tiff.mutableCopy;
    cropImgDictTiff[(NSString *)kCGImagePropertyOrientation] = [self p_imageOrientation:image.imageOrientation];
    cropImgDict[(NSString *)kCGImagePropertyTIFFDictionary] = cropImgDictTiff.copy;
        
    // 3. 裁剪图片. 新建一个画布, 尺寸是自定义裁剪后图片的尺寸, 图片的绘制起点是根据裁剪后图片在原图中的位置计算的. 在画布中获取裁剪后图片.
    UIImage *cropImg = image;
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(image.size.width * self.didCaptureScale, image.size.width *  1 / self.didCaptureRatio * self.didCaptureScale), NO, self.didCaptureScale);
        
    [image drawAtPoint:CGPointMake(0, (image.size.width * 1 / self.didCaptureRatio - image.size.height) / 2)];
    cropImg = UIGraphicsGetImageFromCurrentImageContext();
        
    UIGraphicsEndImageContext();    
    
    // 4. 将裁剪后图片(只有图片画面信息)和图片属性关联起来, 得到destRef
    CFMutableDataRef createRef = CFDataCreateMutable(CFAllocatorGetDefault(), 0);
    
    CGImageDestinationRef destRef = CGImageDestinationCreateWithData(createRef, kUTTypeJPEG, 1, NULL);
    if (self.isRaw) {
        destRef = CGImageDestinationCreateWithData(createRef, kUTTypePNG, 1, NULL);
    }
    
    CFDictionaryRef cfDictRef = (__bridge CFDictionaryRef)cropImgDict;
    CGImageDestinationAddImage(destRef, cropImg.CGImage, cfDictRef);
    
    if (!CGImageDestinationFinalize(destRef)) {
        NSLog(@"ERROR: fail in CGImageDestinationFinalize");
    }
    
    CFRelease(destRef);
    
    // 5. 记录得到的Data, 用于后续存到URL
    self.cropImgData = (__bridge NSData *)createRef;
}

// 自定义方向,目前只用到UIImageOrientationUp,其他的尚未测试
- (NSNumber *)p_imageOrientation:(UIImageOrientation)orientation {
    CGImagePropertyOrientation resOri = kCGImagePropertyOrientationUp;
    switch (orientation) {
        case UIImageOrientationUp:
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored: {
            resOri = kCGImagePropertyOrientationUp;
            break;
        }
        case UIImageOrientationLeft: 
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:{
            // 顺时针转90度
            resOri = kCGImagePropertyOrientationRight;
            break;
        }
        default:
            break;
    }
    
    NSNumber *res = [NSNumber numberWithInt:resOri];
    return res;
}

获取data之后,如果想转成UIImage就用UIImage的imageWithData:方法,如果想存储文件,需要写文件URL路径或者filePath,URL示例如下:

objectivec 复制代码
NSError *writeError = nil;
[self.cropImgData writeToURL:self.yourURL options:kNilOptions error:&writeError];

补充一下:

不需要保存图片文件的话,不用复制Exif字典和Tiff字典,也不用得到destRef和data。

drawInRect:会导致裁剪图片在画布上拉伸,可能是因为画布尺寸改变,draw的却还是原图,所以我用drawAtPoint:方法。

UIGraphicsBeginImageContextWithOptions的scale是绘制图片的缩放比例,如果scale不是1.0,要注意size的宽高都要乘以它。

如果该项目是用在相册存储图片的情况,需要保证URL存在且含有data。如果出现PHPhotosErrorDomain Code=-1 "(null)"这种报错,说明URL中读不到数据,需要检查上面代码的image和cropImage和cropData是否有数据,是否写入了URL。

如果图片的方向不正确,被旋转了,需要检查获取图片方向、Tiff字典中的方向是否正确。

相关推荐
卢锡荣1 天前
LDR6021Q 车规级 Type‑C PD 控制芯片:一芯赋能,边充边传,稳驭全场景
c语言·开发语言·ios·计算机外设·电脑
2501_907136821 天前
iOS任意版本号APP下载
ios·软件需求
denggun123451 天前
结构化并发(Structured Concurrency)
开发语言·ios·swift
weixin_403810131 天前
EasyClick iOS USB版本蓝牙点击坐标代码
ios·自动化·代理模式
良逍Ai出海1 天前
Xcode 26来AI了:iOS独立开发者3步接入实测
人工智能·ios·xcode
denggun123451 天前
Swift6.0为主版本小版本迭代
ios·swift
denggun123451 天前
Swift 版本历年更新记录(核心里程碑 + 关键特性)
开发语言·ios·swift
坚持学习前端日记1 天前
Agent AI 后端接口对接与大模型适配指南
前端·人工智能·python·ios
denggun123451 天前
基于 async/await 的 Swift 并发模型重构
ios·swift
ITKEY_2 天前
appstore上架-预览和截屏
ios·appstore