距离上次博客时间已经有十天左右,过了那么久才有时间来写博客,顿时觉得坚持还是很困难的!!!
这次开发中遇到一个很头疼的问题,是图片压缩的问题,先说下我们的要求,我们要求图片要在600x400的尺寸,如果在这个范围内就不作处理,如果比这个尺寸大,就要改变尺寸大小。同时要保持图片的大小要在50K之内。。。
废话不说了上代码,请路过的大神来指点下,因为我的图片问题还未完全解决,上传的时候有的会被压缩到80K左右,还是要改善代码的。。。。
+ (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize
{
//image是需要改变的image,asize是需要改变的尺寸,我们的是600x400.
UIImage *newImage = nil;
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;
}