iOS:圖片上傳時兩種圖片壓縮方式的比較

來源:互聯網
上載者:User

標籤:

上傳圖片不全面的想法:把圖片儲存到本地,然後把圖片的路徑上傳到伺服器,最後又由伺服器把路徑返回,這種方式不具有擴充性,如果使用者換了手機,那麼新手機的沙箱中就沒有伺服器返回的圖片路徑了,此時就無法擷取之前已經上傳了的頭像了,在項目中明顯的不可行。

上傳圖片的正確方式:上傳頭像到伺服器一般是將圖片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:圖片上傳時兩種圖片壓縮方式的比較

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.