上傳圖片不全面的想法:把圖片保存到本地,而後把圖片的路徑上傳到服務器,最後又由服務器把路徑返回,這種方式不具備擴展性,若是用戶換了手機,那麼新手機的沙盒中就沒有服務器返回的圖片路徑了,此時就沒法獲取以前已經上傳了的頭像了,在項目中明顯的不可行。服務器
上傳圖片的正確方式:上傳頭像到服務器通常是將圖片NSData上傳到服務器,服務器返回一個圖片NSString地址,以後再將NSString的路徑轉爲url並經過url請求去更新用戶頭像(用戶頭像此時更新的即是NSString)app
代碼爲:函數
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的區別url
在Iphone上有兩種讀取圖片數據的簡單方法: UIImageJPEGRepresentation和UIImagePNGRepresentation. spa
UIImageJPEGRepresntation:code
UIImageJPEGRepresentation方法在耗時上比較少 而UIImagePNGRepresentation耗時操做時間比較長orm
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)infoblog
使用UIImagePNGRepresentation取得照片時候可能會形成卡頓的現象圖片
在Iphone上有兩種讀取圖片數據的簡單方法: UIImageJPEGRepresentation和UIImagePNGRepresentation. ip
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,並可根據本身的實際使用場景,設置壓縮係數,進一步下降圖片數據量大小.