最近公司处理图片 前端上传的时候 总是会出现图片上传失败 我们用的是base64和后台交互的,但是base64有大小限制 大约在750--800k之间,超过这个就会无法跟后台进行正常的请求交互.而我们的客户群体又是比较广泛,谁也不知道上帝会给你传多大的照片,而我作为开发,背锅那是肯定的了.为了解决上帝的烦恼呢,就不停地筛选查看文献,最终在俩位大神的文章帮助下自己综合了一下(http://www.jb51.net/article/89491.htm和http://blog.csdn.net/u012603758/article/details/52787225).
代码如下(自己写了个分类扩展)
.h
#import<UIKit/UIKit.h>
@interface UIImage (YZJImageScale)
//image: 处理的图片
//kb:处理后的大小 单位kb
//size:处理后的尺寸(压之后 还大于kb的话才会缩)
+(NSData*)scaleImage:(UIImage *)image toKb:(NSInteger)kb withSize:(CGSize )size;
@end
.m
#import "UIImage+YZJImageScale.h"
@implementation UIImage (YZJImageScale)
+(NSData *)scaleImage:(UIImage *)image toKb:(NSInteger)kb withSize:(CGSize )size{
//压
if (kb<1) {
return nil;
}
kb*=1024;
CGFloat compression = 0.4f;
CGFloat maxCompression = 0.1f;
NSData *imageData = UIImageJPEGRepresentation(image, compression);
while ([imageData length] > kb && compression > maxCompression) {
compression -= 0.1;
imageData = UIImageJPEGRepresentation(image, compression);
}
//缩
if ([imageData length]>kb&&compression<0.1) {
UIImage *newImage=[UIImage imageWithData:imageData];
UIImage *targetImg=[[self new] imageByScalingAndCroppingForSize:size withSourceImage:newImage];
imageData= UIImageJPEGRepresentation(targetImg, 0.7f);
}
return imageData;
}
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize withSourceImage:(UIImage *)sourceImage
{
UIImage *newImage = nil;
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
if (CGSizeEqualToSize(imageSize, targetSize) == NO)
{
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;
if (widthFactor > heightFactor)
scaleFactor = widthFactor; // scale to fit height
else
scaleFactor = heightFactor; // scale to fit width
scaledWidth= width * scaleFactor;
scaledHeight = height * scaleFactor;
// center the image
if (widthFactor > heightFactor)
{
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
}
else if (widthFactor < heightFactor)
{
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
}
UIGraphicsBeginImageContext(targetSize); // this will crop
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width= scaledWidth;
thumbnailRect.size.height = scaledHeight;
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
if(newImage == nil)
NSLog(@"could not scale image");
//pop the context to get back to the default
UIGraphicsEndImageContext();
return newImage;
}
@end