等比例压缩
-(UIImage*) imageCompressForSize:(UIImage*)sourceImage targetSize:(CGSize)size{UIImage*newImage =nil;CGSizeimageSize = sourceImage.size;CGFloatwidth = imageSize.width;CGFloatheight = imageSize.height;CGFloattargetWidth = size.width;CGFloattargetHeight = size.height;CGFloatscaleFactor =0.0;CGFloatscaledWidth = targetWidth;CGFloatscaledHeight = targetHeight;CGPointthumbnailPoint =CGPointMake(0.0,0.0);if(CGSizeEqualToSize(imageSize, size) ==NO){CGFloatwidthFactor = targetWidth / width;CGFloatheightFactor = targetHeight / height;if(widthFactor > heightFactor){
scaleFactor = widthFactor;
}else{
scaleFactor = heightFactor;
}
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;if(widthFactor > heightFactor){
thumbnailPoint.y = (targetHeight - scaledHeight) *0.5;
}elseif(widthFactor < heightFactor){
thumbnailPoint.x = (targetWidth - scaledWidth) *0.5;
}
}UIGraphicsBeginImageContext(size);CGRectthumbnailRect =CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;
[sourceImage drawInRect:thumbnailRect];
newImage =UIGraphicsGetImageFromCurrentImageContext();if(newImage ==nil){NSLog(@"scale image fail");
}UIGraphicsEndImageContext();returnnewImage;
}
-(UIImage*) imageCompressForWidth:(UIImage*)sourceImage targetWidth:(CGFloat)defineWidth{UIImage*newImage =nil;CGSizeimageSize = sourceImage.size;CGFloatwidth = imageSize.width;CGFloatheight = imageSize.height;CGFloattargetWidth = defineWidth;CGFloattargetHeight = height / (width / targetWidth);CGSizesize =CGSizeMake(targetWidth, targetHeight);CGFloatscaleFactor =0.0;CGFloatscaledWidth = targetWidth;CGFloatscaledHeight = targetHeight;CGPointthumbnailPoint =CGPointMake(0.0,0.0);if(CGSizeEqualToSize(imageSize, size) ==NO){CGFloatwidthFactor = targetWidth / width;CGFloatheightFactor = targetHeight / height;if(widthFactor > heightFactor){
scaleFactor = widthFactor;
}else{
scaleFactor = heightFactor;
}
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;if(widthFactor > heightFactor){
thumbnailPoint.y = (targetHeight - scaledHeight) *0.5;
}elseif(widthFactor < heightFactor){
thumbnailPoint.x = (targetWidth - scaledWidth) *0.5;
}
}UIGraphicsBeginImageContext(size);CGRectthumbnailRect =CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;
[sourceImage drawInRect:thumbnailRect];
newImage =UIGraphicsGetImageFromCurrentImageContext();if(newImage ==nil){NSLog(@"scale image fail");
}UIGraphicsEndImageContext();returnnewImage;
}