最近公司處理圖片 前端上傳的時候 總是會出現圖片上傳失敗? 我們用的是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