IOS :图像压缩

来源:互联网 发布:java base64 应用 编辑:程序博客网 时间:2024/05/08 14:21

.h文件:

#import <Foundation/Foundation.h>


@interface UtilMethods : NSObjects


- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize withImage:(UIImage *)sourceImage;


@end

.m文件:

#import "UtilMethods.h"


@implementation UtilMethods


- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize withImage:(UIImage *)sourceImage

{

UIImage *newImage = nil;

CGFloat width =sourceImage.size.width;

CGFloat height =sourceImage.size.height;

CGFloat targetWidth = targetSize.width;

CGFloat targetHeight = targetSize.height;

CGFloat scaleFactor = 0.0;

CGFloat scaledX = 0.0;

CGFloat scaledY = 0.0;

CGFloat scaledWidth = targetWidth;

CGFloat scaledHeight = targetHeight;

CGPointthumbnailRect = CGSizeMake(0.0,0.0,0.0,0.0);

if (CGSizeEqualToSize(imageSize, targetSize) == NO)

{

CGFloat widthFactor = targetWidth / width;

CGFloat heightFactor = targetHeight / height;

if (widthFactor > heightFactor)

scaleFactor =heightFactor; // scale to fitwidth

else

scaleFactor =widthFactor; // scale to fitheight

scaledWidth= width * scaleFactor;

scaledHeight = height * scaleFactor;

// center the image

if (widthFactor > heightFactor)

{

scaledY = (targetHeight - scaledHeight)/2;

}

else if (widthFactor < heightFactor)

{

scaledX = (targetWidth - scaledWidth)/2;

}

}

UIGraphicsBeginImageContext(targetSize); 


thumbnailRect = CGSizeMake(scaledX,scaledY,scaledWidth,scaledHeight);

[sourceImage drawInRect:thumbnailRect];

newImage = UIGraphicsGetImageFromCurrentImageContext();


UIGraphicsEndImageContext();

return newImage;

}


@end