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

相关推荐
我是谁的程序员3 小时前
Mac 上生成 AppStoreInfo.plist 文件,App Store 上架
后端·ios
sweet丶4 小时前
微信Matrix 卡顿监控原理梳理与图解
ios
2501_916007476 小时前
iOS开发中抓取HTTPS请求的完整解决方法与步骤详解
android·网络协议·ios·小程序·https·uni-app·iphone
ZZH_AI项目交付10 小时前
我把 AI 最容易改坏真实 App 的地方,整理成了 skills
人工智能·ios·app
00后程序员张10 小时前
Windows 下怎么生成 AppStoreInfo.plist?不依赖 Xcode 的方法
ide·macos·ios·小程序·uni-app·iphone·xcode
原鸣清11 小时前
iOS 自定义 Markdown 渲染实践:从成品库到可魔改 Demo
ios
Daniel_Coder11 小时前
iOS Widget 开发-18:Widget 的 SwiftUI 视图适配与设计
ios·swiftui·swift·widget·widgetcenter
Daniel_Coder11 小时前
iOS Widget 开发-17:Widget 错误处理与空状态设计
ios·swift·widget·widgetcenter
wjm04100612 小时前
简单谈谈ios开发中的UI
开发语言·ios·swift
恋猫de小郭13 小时前
Flutter 3.44 发布啦,超级大版本更新!!!
android·flutter·ios