Image compression algorithm and Image Compression Algorithm
# Pragma mark image scale utility complete!
-(UIImage *) imageByScalingToMaxSize :( UIImage *) sourceImage {
If (sourceImage. size. width <ORIGINAL_MAX_WIDTH) return sourceImage;
CGFloat btWidth = 0.0f;
CGFloat btHeight = 0.0f;
If (sourceImage. size. width> sourceImage. size. height ){
BtHeight = ORIGINAL_MAX_WIDTH;
BtWidth = sourceImage. size. width * (ORIGINAL_MAX_WIDTH/sourceImage. size. height );
} Else {
BtWidth = ORIGINAL_MAX_WIDTH;
BtHeight = sourceImage. size. height * (ORIGINAL_MAX_WIDTH/sourceImage. size. width );
}
CGSize targetSize = CGSizeMake (btWidth, btHeight );
Return [self imageByScalingAndCroppingForSourceImage: sourceImage targetSize: targetSize];
}
-(UIImage *) imageByScalingAndCroppingForSourceImage :( UIImage *) sourceImage targetSize :( CGSize) targetSize {
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 {
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 (@ "cocould not scale image ");
// Pop the context to get back to the default
UIGraphicsEndImageContext ();
Return newImage;
}