您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 相簿選圖後壓縮上傳的完整實作

編輯:iOS 開發綜合

行動裝置網路不穩、流量有限,選完照片直接上傳原圖往往會遇到上傳緩慢甚至失敗的問題。實務上的標準做法是:選圖 → 壓縮 → 上傳。以下用一個完整流程示範。

一、接收選圖結果並上傳

#pragma mark - 相機 / 相簿選圖完成
- (void)imagePickerController:(UIImagePickerController *)picker
    didFinishPickingMediaWithInfo:(NSDictionary<NSString *, id> *)info {
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    self.currentTapCell.photoManageImgView.image = image;

    NSIndexPath *indexPath = [self.baseTable indexPathForCell:self.currentTapCell];
    NSString *key = [NSString stringWithFormat:@"ineed%u%u", indexPath.row, indexPath.section];

    [[NetEngineHelper shareNetEngine]
        postUploadWithUrl:k_uploadPhoto_url
                    image:image
                 fileName:[NSString stringWithFormat:@"%@.png", key]
                 fileType:@"PNG/JPEG/JPG"
                  success:^(id response) {
            if ([response[@"STATUS"] intValue] != 0) {
                NSString *str = response[@"ERRORDESC"] ? response[@"ERRORDESC"] : @"系統異常";
                [AlertHelper shareAlertHelper].onVC = self;
                [AlertHelper shareAlertHelper].alertTitle = str;
                [AlertHelper shareAlertHelper].alertMessage = nil;
                [[AlertHelper shareAlertHelper] alertVcWithSureAction:^(id response) {}];
            } else {
                [AlertHelper shareAlertHelper].onVC = self;
                [AlertHelper shareAlertHelper].alertTitle = @"上傳成功";
                [AlertHelper shareAlertHelper].alertMessage = nil;
                [[AlertHelper shareAlertHelper] alertVcWithSureAction:^(id response) {}];

                if ([self.currentTapCell.photoDescribeLable.text isEqualToString:@"上傳診斷證明"]) {
                    [self.successUploadDic setValue:response[@"FILEID"] forKey:@"PROVEID"];
                }
                if ([self.currentTapCell.photoDescribeLable.text isEqualToString:@"上傳病歷首頁"]) {
                    [self.successUploadDic setValue:response[@"FILEID"] forKey:@"CASEHOMEID"];
                }
                NSLog(@"上傳結果 %@", response);
            }
        }
                     fail:^(NSError *error) {
            [AlertHelper shareAlertHelper].onVC = self;
            [AlertHelper shareAlertHelper].alertTitle = error.userInfo[@"NSLocalizedDescription"];
            [AlertHelper shareAlertHelper].alertMessage = nil;
            [[AlertHelper shareAlertHelper] alertVcWithSureAction:^(id response) {}];
        }];

    [self dismissViewControllerAnimated:YES completion:^{}];
}

二、封裝上傳方法

重點在最後那段 constructingBodyWithBlock::壓縮與否完全由這裡決定。

/** 上傳檔案 */
- (void)postUploadWithUrl:(NSString *)urlStr
                    image:(UIImage *)image
                 fileName:(NSString *)fileName
                 fileType:(NSString *)fileTye
                  success:(Success)success
                     fail:(Faile)fail {
    NSString *resultStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:
                           [NSCharacterSet URLQueryAllowedCharacterSet]];
    self.success = success;
    self.failer = fail;

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes =
        [NSSet setWithObjects:@"text/html", @"application/json", @"text/plain", nil];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager.securityPolicy setAllowInvalidCertificates:YES];

    UIApplication *application = [UIApplication sharedApplication];
    application.networkActivityIndicatorVisible = YES;

    [manager POST:resultStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        // 壓縮關鍵:0.02 的壓縮品質
        NSData *imgData = UIImageJPEGRepresentation(image, 0.02);
        [formData appendPartWithFileData:imgData
                                    name:@"FILENAME"
                                fileName:fileName
                                mimeType:fileTye];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        success(responseObject);
        application.networkActivityIndicatorVisible = NO;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        fail(error);
        application.networkActivityIndicatorVisible = NO;
    }];
}

三、關於壓縮品質的取捨

UIImageJPEGRepresentation(image, quality) 的 quality 範圍是 0.0 到 1.0,數值越低檔案越小、畫質越差。範例中的 0.02 屬於極端壓縮,只適合「醫療證明照片這類僅供人工查看、不求細節」的場景;一般使用者可見的圖片建議落在 0.5 到 0.8 之間。

只調 quality 其實還不夠。更有效的做法是「先降尺寸,再壓品質」,因為 JPEG 檔案大小與像素總量高度相關:

CGFloat maxWidth = 1280;
CGSize newSize = image.size;
if (newSize.width > maxWidth) {
    newSize.height = maxWidth * image.size.height / image.size.width;
    newSize.width = maxWidth;
}
UIGraphicsBeginImageContextWithOptions(newSize, NO, 1.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *resized = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

NSData *imgData = UIImageJPEGRepresentation(resized, 0.7);

另外提醒三個實務細節:setAllowInvalidCertificates:YES 會關掉 HTTPS 憑證驗證,等於放棄傳輸安全,只該用於測試環境,正式上線務必移除;上傳過程中應顯示進度或 loading,避免使用者誤觸重複上傳;最後,AFNetworking 的 AFHTTPRequestOperationManager 已停止維護,新專案請改用 AFHTTPSessionManager 或 URLSession。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved