今天来公司加班,准备搞一下聊天时发送拍照图片慢的问题,因为之前也做了一些对图片的处理,但是发送的过程中存在延迟。之前只是对图片进行了压的动作,通过判断data.length的长度,来进行压.
<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>
后来通过百度才发现如果想要压缩到更小,就要对图片自身进行裁剪,于是才想到这个方法
<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>通过这两个方法的处理,在进行图片发送就变得很快了。