iOS 系统照相机和相册照片内存大小的计算

最近公司开发遇到一个需求, 需要判断照片的大小 不能超过2M,从网上找了好多方法,都发现计算出来的结果和实际大小不一样。后来发现TZImagePickerController里有相关类似方法,于是参考着,抽取出来,作为笔记。话不多说,直接上代码。

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    NSDictionary *meta = [info objectForKey:UIImagePickerControllerMediaMetadata];
    __block NSInteger dataLength = 0;
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.resizeMode = PHImageRequestOptionsResizeModeFast;
    options.networkAccessAllowed = YES;
    //self.location 是CLLocation类型 系统定位得到

    WeakSelf
    [self getImageAssetWithImage:image meta:meta location:self.location completion:^(PHAsset *asset, NSError *error) {
        [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
            dataLength += imageData.length;
            NSString *bytes = [self getBytesFromDataLength:dataLength];//bytes就是计算出来的照片大小
        }];
    }];
    _uploadImage = image;
    _uploadImageView.image = image;
    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
    [self commitButtonStatusSet];
}
- (void)getImageAssetWithImage:(UIImage *)image meta:(NSDictionary *)meta location:(CLLocation *)location completion:(void (^)(PHAsset *asset, NSError *error))completion {
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0f);
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL);
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss-SSS"];
    NSString *path = [NSTemporaryDirectory() stringByAppendingFormat:@"image-%@.jpg", [formater stringFromDate:[NSDate date]]];
    NSURL *tmpURL = [NSURL fileURLWithPath:path];
    CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)tmpURL, kUTTypeJPEG, 1, NULL);
    CGImageDestinationAddImageFromSource(destination, source, 0, (__bridge CFDictionaryRef)meta);
    CGImageDestinationFinalize(destination);
    CFRelease(source);
    CFRelease(destination);
    
    __block NSString *localIdentifier = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        PHAssetChangeRequest *request = [PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:tmpURL];
        localIdentifier = request.placeholderForCreatedAsset.localIdentifier;
        if (location) {
            request.location = location;
        }
        request.creationDate = [NSDate date];
    } completionHandler:^(BOOL success, NSError *error) {
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
         dispatch_async(dispatch_get_main_queue(), ^{
             if (success && completion) {
                 PHAsset *asset = [[PHAsset fetchAssetsWithLocalIdentifiers:@[localIdentifier] options:nil] firstObject];
                 completion(asset, nil);
                 
             } else if (error) {
                NSLog(@"保存照片出错:%@",error.localizedDescription);
                if (completion) {
                    completion(nil, error);
                }
            }
        });
    }];
}
- (NSString *)getBytesFromDataLength:(NSInteger)dataLength {
    NSString *bytes;
    if (dataLength >= 0.1 * (1024 * 1024)) {
        bytes = [NSString stringWithFormat:@"%0.1fM",dataLength/1024/1024.0];
    } else if (dataLength >= 1024) {
        bytes = [NSString stringWithFormat:@"%0.0fK",dataLength/1024.0];
    } else {
        bytes = [NSString stringWithFormat:@"%zdB",dataLength];
    }
    return bytes;
}

最后感谢TZImagePickerController作者提供的方法和思路

推荐阅读更多精彩内容

  • 现在很多网站已经逐渐使用HTTPS来代替HTTP来保障通信安全。和HTTP相比,HTTPS不再采用明文传输数据,第...
    优雨阅读 564评论 0 1
  • 看见比我优秀的人,第一反应不是羡慕,是不安。 原来不止我一个会迷茫,今天朋友说她最近很迷茫,觉得现在学的东西对未来...
    孤单单的指挥家阅读 61评论 0 0
  • 生活的潦草, 写的也随性。 在这世界上活的无味, 白天疲惫, 夜里不安分, 或许是去梦里寻找美。 白天的虚伪, 深...
    孤笔题岁月阅读 62评论 0 1