距離上次博客時間已經有十天左右,過了那麼久纔有時間來寫博客,頓時以爲堅持仍是很困難的!!!圖片
此次開發中遇到一個很頭疼的問題,是圖片壓縮的問題,先說下咱們的要求,咱們要求圖片要在600x400的尺寸,若是在這個範圍內就不做處理,若是比這個尺寸大,就要改變尺寸大小。同時要保持圖片的大小要在50K以內。。。開發
廢話不說了上代碼,請路過的大神來指點下,由於個人圖片問題還未徹底解決,上傳的時候有的會被壓縮到80K左右,仍是要改善代碼的。。。。get
+ (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize 博客
{it
//image是須要改變的image,asize是須要改變的尺寸,咱們的是600x400.io
UIImage *newImage = nil;im
CGSize imageSize = image.size;圖片壓縮
CGFloat width = imageSize.width;時間
CGFloat height = imageSize.height;大神
CGFloat targetWidth = asize.width;
CGFloat targetHeight = asize.height;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
CGFloat sacleWidth = 0.0;
CGFloat sacleHeigh = 0.0;
if(CGSizeEqualToSize(imageSize, asize) == NO){
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;
CGFloat asizeFactor = targetWidth / targetHeight;
CGFloat sizeFactor = width / height;
//若是比例比現有比例高
if(sizeFactor > asizeFactor){
if(width < targetWidth){
//高度比標準小 寬度一定比標準小
sacleWidth = width;
sacleHeigh = height;
}else{
//寬度比標準大 計算高度
sacleWidth = 400;
sacleHeigh = height / (width / targetWidth);
}
}
else{
if(height < targetHeight){
//高度比標準小 寬度一定比標準小
sacleWidth = width;
sacleHeigh = height;
}else{
//寬度比標準大 計算高度
sacleHeigh = 400;
sacleWidth = width / (height / targetHeight);
}
}
if(widthFactor > heightFactor){
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
}else if(widthFactor < heightFactor){
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
asize = CGSizeMake(sacleWidth, sacleHeigh);
}
UIGraphicsBeginImageContext(asize);
UIImage *imageD = nil;
if(newImage == nil){
NSLog(@"scale image fail");
}
[image drawInRect:CGRectMake(0,0,asize.width,asize.height)];
UIImage* iamgeNews = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
imageD = [self imageWithJPGRepresentTationWith:iamgeNews withSacle:0.6f];
return imageD;
}
// 對圖片進行壓縮
+ (UIImage *)imageWithJPGRepresentTationWith:(UIImage *)image withSacle:(CGFloat)sacle {
NSData *imageData = UIImageJPEGRepresentation(image, sacle);
NSData *imageData1 = UIImageJPEGRepresentation(image, 1.0f);
NSData *imageData0 = UIImageJPEGRepresentation(image, 0.0f);
UIImage *imag = nil;
//大於50k壓縮,小於50k不做處理
if(imageData.length / 1000 > 50){
NSData *imageData2 = UIImageJPEGRepresentation(image, sacle);
imag = [UIImage imageWithData:imageData2];
NSLog(@"%ld",(long)imageData2.length / 1000);
}else{
imag = [UIImage imageWithData:imageData];
}
NSLog(@"%ld",(long)imageData.length / 1000);
NSLog(@"%ld",(long)imageData1.length / 1000);
NSLog(@"%ld",(long)imageData0.length / 1000);
return imag;
}