您的位置:首页 > 移动开发 > IOS开发

IOS :图像压缩

2012-11-30 17:11 120 查看
.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;

CGPoint
thumbnailRect = 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 fit
width

else

scaleFactor =
widthFactor; // scale to fit
height

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: