這是官方的解釋:
UIImagePNGRepresentation(UIImage*__nonnullimage);// return image as PNG. May return nil if image has no CGImageRef or invalid bitmap format]
UIImageJPEGRepresentation(UIImage*__nonnullimage,CGFloatcompressionQuality);//return image as JPEG. May return nil if image has no CGImageRef or invalid bitmap format. compression is 0(most)..1(least)
UIImageJPEGRepresentation方法需要兩個(gè)參數(shù):圖片的引用和壓縮系數(shù),而UIImagePNGRepresentation方法僅僅需要一個(gè)參數(shù):圖片的引用。UIImagePNGRepresentation方法在耗時(shí)上比UIImageJPEGRepresentation耗時(shí),圖片數(shù)據(jù)量更大,使用 UIImagePNGRepresentation讀取照片數(shù)據(jù)的時(shí)候有可能會(huì)照成卡頓。兩個(gè)方法返回的數(shù)據(jù)都是NSData類型。
例如:
同樣是讀取攝像頭拍攝的圖片,UIImagePNGRepresentation(UIImage *image)返回的數(shù)據(jù)量大小為199K,而UIImageJPEGRepresentation(UIImage *image,1.0)返回的數(shù)據(jù)量只有140K,比前者少了50多K;而且如果對(duì)圖片的質(zhì)量要求不那么高的話,還可以通過設(shè)置壓縮系數(shù)進(jìn)一步減少數(shù)據(jù)量,降低壓縮系數(shù)后UIImageJPEGRepresentation(UIImage *image, 0.5),返回的數(shù)據(jù)大小只有11K,大大壓縮了圖片數(shù)據(jù)量,而且從視圖角度看,圖片的質(zhì)量并沒有明顯降低。所以,在讀區(qū)圖片數(shù)據(jù)內(nèi)容的時(shí)候,建議優(yōu)先使用方法UIImageJPEGRepresentation(UIImage *image, CGFloatcompressionQuality)
代碼:
NSData *data = nil; if(!UIImagePNGRepresentation(image)) { data =UIImageJPEGRepresentation(image,0.1); }else{ data =UIImagePNGRepresentation(image); }