今天來(lái)公司加班,準(zhǔn)備搞一下聊天時(shí)發(fā)送拍照?qǐng)D片慢的問(wèn)題,因?yàn)橹耙沧隽艘恍?duì)圖片的處理,但是發(fā)送的過(guò)程中存在延遲。之前只是對(duì)圖片進(jìn)行了壓的動(dòng)作,通過(guò)判斷data.length的長(zhǎng)度,來(lái)進(jìn)行壓.
<pre>
-(NSData)handleImage:(UIImage)originImage{
NSData *data = UIImageJPEGRepresentation(originImage, 1);
NSData *newData = nil;
CGFloat compression = 0.9f;
if (data.length<COMPRESS_FIRST_SIZE) {
newData = data;
}else if(data.length<COMPRESS_SECOND_SIZE){
newData = UIImageJPEGRepresentation(originImage, FACTOR_BEYOND_FIRST_SIZE/100.0f);
}else if(data.length<COMPRESS_THIRD_SIZE){
newData = UIImageJPEGRepresentation(originImage, FACTOR_BEYOND_SECOND_SIZE/100.0f);
}else if(data.length<COMPRESS_FOURTH_SIZE){
newData = UIImageJPEGRepresentation(originImage, FACTOR_BEYOND_THIRD_SIZE/100.0f);
}else if(data.length<COMPRESS_FIVE_SIZE){
compression *= 0.7;
newData = UIImageJPEGRepresentation([[self class] compressImage:originImage newWidth:originImage.size.width*compression], FACTOR_BEYOND_FIVE_SIZE/100.0f);
}else{
//newData = UIImageJPEGRepresentation(originImage, FACTOR_BEYOND_SIX_SIZE/1000.0f);
compression *= 0.9;
newData = UIImageJPEGRepresentation([[self class] compressImage:originImage newWidth:originImage.size.width*compression], FACTOR_BEYOND_FIVE_SIZE/100.0f);
}
return newData;
}
</pre>
后來(lái)通過(guò)百度才發(fā)現(xiàn)如果想要壓縮到更小,就要對(duì)圖片自身進(jìn)行裁剪,于是才想到這個(gè)方法
<pre>+ (UIImage *)compressImage:(UIImage *)image newWidth:(CGFloat)newImageWidth
{
if (!image) return nil;
float imageWidth = image.size.width;
float imageHeight = image.size.height;
float width = newImageWidth;
float height = image.size.height/(image.size.width/width);
float widthScale = imageWidth /width;
float heightScale = imageHeight /height;
UIGraphicsBeginImageContext(CGSizeMake(width, height));
if (widthScale > heightScale) {
[image drawInRect:CGRectMake(0, 0, imageWidth /heightScale , height)];
}
else {
[image drawInRect:CGRectMake(0, 0, width , imageHeight /widthScale)];
}
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}</pre>通過(guò)這兩個(gè)方法的處理,在進(jìn)行圖片發(fā)送就變得很快了。