让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字典中的方向是否正确。

相关推荐
鸿蒙布道师16 小时前
鸿蒙NEXT开发动画案例3
android·ios·华为·harmonyos·鸿蒙系统·arkui·huawei
鸿蒙布道师16 小时前
AI原生手机:三大技术阵营的终极对决与未来展望
android·人工智能·ios·华为·智能手机·ai-native·hauwei
Echo-潔17 小时前
iOS创建Certificate证书、制作p12证书流程
ios·ios 生成app打包证书
yangpipi-1 天前
10.王道_HTTP
网络协议·http·ios
鸿蒙布道师2 天前
鸿蒙NEXT开发动画案例2
android·ios·华为·harmonyos·鸿蒙系统·arkui·huawei
I烟雨云渊T2 天前
iOS 模块化开发流程
ios
刘小哈哈哈2 天前
Lost connect to debugger on ‘iphone‘
ios·iphone
I烟雨云渊T2 天前
iOS蓝牙技术实现及优化
macos·ios·cocoa
大力水手~2 天前
微信小程序上传视频,解决ios上传完video组件无法播放
ios·微信小程序·音视频
小鹿撞出了脑震荡2 天前
「OC」源码学习——objc_class的bits成员探究
学习·ios·objective-c