標籤:
上傳圖片不全面的想法:把圖片儲存到本地,然後把圖片的路徑上傳到伺服器,最後又由伺服器把路徑返回,這種方式不具有擴充性,如果使用者換了手機,那麼新手機的沙箱中就沒有伺服器返回的圖片路徑了,此時就無法擷取之前已經上傳了的頭像了,在項目中明顯的不可行。
上傳圖片的正確方式:上傳頭像到伺服器一般是將圖片NSData上傳到伺服器,伺服器返回一個圖片NSString地址,之後再將NSString的路徑轉為url並通過url請求去更新帳戶圖片(帳戶圖片此時更新的便是NSString)
代碼為:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; // 佈建要求格式 manager.requestSerializer = [AFJSONRequestSerializer serializer]; // 設定返回格式 manager.responseSerializer = [AFJSONResponseSerializer serializer];[manager POST:[NSString stringWithFormat:@"%@%@", XLImageServerHost, functionName] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {/////傳的圖片資料放這裡 NSData *eachImgData = UIImageJPEGRepresentation(image, 0.5); [formData appendPartWithFileData :eachImgData name : @"upload" fileName : @"picture.jpg" mimeType : @"image/jpeg" ]; } success:^(AFHTTPRequestOperation *operation, id responseObject) { ///請求成功 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { ///請求失敗 }];
現在來介紹一下:UIImageJPEGRepresntation 和 UIImagePNGRepresontation的區別
在Iphone上有兩種讀取圖片資料的簡單方法: UIImageJPEGRepresentation和UIImagePNGRepresentation.
UIImageJPEGRepresntation:
UIImageJPEGRepresentation方法在耗時上比較少 而UIImagePNGRepresentation耗時操作時間比較長
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
使用UIImagePNGRepresentation取得照片時候可能會造成卡頓的現象
在Iphone上有兩種讀取圖片資料的簡單方法: UIImageJPEGRepresentation和UIImagePNGRepresentation.
UIImagePNGRepresontation:
UIImageJPEGRepresentation函數需要兩個參數:圖片的引用和壓縮係數.而UIImagePNGRepresentation只需要圖片引用作為參數.通過在實際使用過程中,比較發現: UIImagePNGRepresentation(UIImage* image) 要比UIImageJPEGRepresentation(UIImage* image, 1.0) 返回的圖片資料量大很多.
譬如,同樣是讀取網路攝影機拍攝的同樣景色的照片, UIImagePNGRepresentation()返回的資料量大小為199K ,而 UIImageJPEGRepresentation(UIImage* image, 1.0)返回的資料量大小隻為140KB,比前者少了50多KB.如果對圖片的清晰度要求不高,還可以通過設定 UIImageJPEGRepresentation函數的第二個參數,大幅度降低圖片資料量.
譬如,剛才拍攝的圖片, 通過調用UIImageJPEGRepresentation(UIImage* image, 1.0)讀取資料時,返回的資料大小為140KB,但更改壓縮係數後,通過調用UIImageJPEGRepresentation(UIImage* image, 0.5)讀取資料時,返回的資料大小隻有11KB多,大大壓縮了圖片的資料量 ,而且從視角角度看,圖片的品質並沒有明顯的降低.因此,在讀取圖片資料內容時,建議優先使用UIImageJPEGRepresentation,並可根據自己的實際使用情境,設定壓縮係數,進一步降低圖片資料量大小.
iOS:圖片上傳時兩種圖片壓縮方式的比較