图片上传服务器的而终极解决方案 【转载】
/** * 动态发布图片压缩 * * @param source_image 原图image * @param maxSize 限定的图片大小 * * @return 返回处理后的图片 */ - (NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize;
先调整分辨率,分辨率可以自己设定一个值,大于的就缩小到这分辨率,小余的就保持原本分辨率。然后在根据最终大小来设置压缩比,比如传入maxSize = 100k,最终计算大概这个大小的压缩比。基本上最终出来的图片数据根据当前分辨率能保持差不多的大小同时不至于太模糊,跟微信,微博最终效果应该是差不多的,代码仍然有待优化!
//传入的第二个参数 是100 代表 100k gzz0706
- (NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize { //先调整分辨率 CGSize newSize = CGSizeMake(source_image.size.width, source_image.size.height); CGFloat tempHeight = newSize.height / 1024; CGFloat tempWidth = newSize.width / 1024; if (tempWidth > 1.0 && tempWidth > tempHeight) { newSize = CGSizeMake(source_image.size.width / tempWidth, source_image.size.height / tempWidth); } else if (tempHeight > 1.0 && tempWidth < tempHeight){ newSize = CGSizeMake(source_image.size.width / tempHeight, source_image.size.height / tempHeight); } UIGraphicsBeginImageContext(newSize); [source_image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)]; UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); //调整大小 NSData *imageData = UIImageJPEGRepresentation(newImage,1.0); NSUInteger sizeOrigin = [imageData length]; NSUInteger sizeOriginKB = sizeOrigin / 1024; if (sizeOriginKB > maxSize) { NSData *finallImageData = UIImageJPEGRepresentation(newImage,0.50); return finallImageData; } return imageData; }