您的位置:首页 > 产品设计 > UI/UE

关于UIImagePickerController读取照片时的卡顿和照片压缩

2014-12-31 18:15 225 查看
UIImagePickerController

-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{

//关闭相册界面 //这个位置解决使用图片时的内存徒增的现象

[picker dismissViewControllerAnimated:YES
completion:nil];

NSString *type = [info
objectForKey:UIImagePickerControllerMediaType];

//当选择的类型是图片

if ([type isEqualToString:@"public.image"])

{

//先把图片转成NSData

UIImage* image = [info
objectForKey:@"UIImagePickerControllerOriginalImage"];

//图片比例压缩的一套方法

CGSize size = [LW_ImageCompression
get_ImageCompressionProportion:image];

image = [image imageByScalingAndCroppingForSize:size];

NSData *data =
UIImagePNGRepresentation(image);

if (data ==
nil)

{

data = UIImageJPEGRepresentation(image,
0.25);

}

//图片保存的路径

//这里将图片放在沙盒的documents文件夹中

NSString * DocumentsPath = [NSHomeDirectory()
stringByAppendingPathComponent:@"Documents"];

//文件管理器

NSFileManager *fileManager = [NSFileManager
defaultManager];

//把刚刚图片转换的data对象拷贝至沙盒中
并保存为image.png

[fileManager createDirectoryAtPath:DocumentsPath
withIntermediateDirectories:YES
attributes:nil
error:nil];

[fileManager createFileAtPath:[DocumentsPath
stringByAppendingString:@"/image.png"]
contents:data attributes:nil];
//GET THE IMAGE

}

}

class :
LW_ImageCompression

#define ScreenHeight [UIScreen mainScreen].bounds.size.height

#define ScreenWidth [UIScreen mainScreen].bounds.size.width

+(CGSize)get_ImageCompressionProportion:(UIImage *)image
{

CGSize size = image.size;

CGFloat HBL = ScreenHeight / size.height;

CGFloat WBL = ScreenWidth / size.width;

if (size.width <=
ScreenWidth && size.height <=
ScreenHeight) {

return size;
}

else if (size.width >
ScreenWidth && size.height <=
ScreenHeight) {
size.width =
ScreenWidth;
size.height = size.height * WBL;

NSString * str = [NSString
stringWithFormat:@"%.0f",size.height];
size.height = [str
floatValue];
}

else if (size.height >
ScreenHeight && size.width <=
ScreenWidth) {
size.height =
ScreenHeight;
size.width = size.width * HBL;

NSString * str = [NSString
stringWithFormat:@"%.0f",size.width];
size.width = [str
floatValue];
}

else if (size.height >
ScreenHeight && size.width >
ScreenWidth) {

if (HBL < WBL) {
size.height =
ScreenHeight;
size.width = size.width * HBL;

NSString * str = [NSString
stringWithFormat:@"%.0f",size.width];
size.width = [str
floatValue];
}

else
{
size.width =
ScreenWidth;
size.height = size.height * WBL;

NSString * str = [NSString
stringWithFormat:@"%.0f",size.height];
size.height = [str
floatValue];
}
}

return size;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: