关于聊天图片的压与缩

今天来公司加班,准备搞一下聊天时发送拍照图片慢的问题,因为之前也做了一些对图片的处理,但是发送的过程中存在延迟。之前只是对图片进行了压的动作,通过判断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>通过这两个方法的处理,在进行图片发送就变得很快了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容