第一个:压缩图片
当我们上传图片到服务器时,需要压缩一下图片的质量。方法如下:
/*
*压缩图片
*/
+ (UIImage *)resizeImageWithImage:(UIImage *)image targetSize:(CGSize)targetSize;
+ (UIImage *)resizeImageWithImage:(UIImage *)image targetSize:(CGSize)targetSize
{
CGSize size = image.size;
CGFloat widthRatio = targetSize.width / image.size.width;
CGFloat heightRatio = targetSize.height / image.size.height;
CGSize newSize;
if (widthRatio > heightRatio) newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio);
else newSize = CGSizeMake(size.width * widthRatio, size.height * widthRatio);
CGRect rect = CGRectMake(0, 0, newSize.width, newSize.height);
UIGraphicsBeginImageContextWithOptions(newSize, NO, 1.0);
[image drawInRect:rect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
第二个,截取人脸部图片
拍摄身份证或者其他有人脸部的图片时,我们可能只需要人脸部分的头像图片。裁剪的方法如下:
/*
*获取脸部图片
*/
+ (CGRect)adjustFaceImageWithRect:(CGRect)rect sourceImage:(UIImage *)sourceImage;
+ (CGRect)adjustFaceImageWithRect:(CGRect)rect sourceImage:(UIImage *)sourceImage
{
CGRect faceRect;
CGFloat widthMargin = rect.size.width/2;;
CGFloat heightMargin = rect.size.height/2;
faceRect.origin.x = MAX(rect.origin.x - widthMargin, 0);
faceRect.origin.y = MAX(rect.origin.y - heightMargin - heightMargin/2, 0) + 20;
faceRect.size.width = MIN(rect.size.width + 2*widthMargin, (CGFloat)(sourceImage.size.width - faceRect.origin.x - 1));
faceRect.size.height = MIN(rect.size.height + 2*heightMargin + heightMargin/2, (CGFloat)(sourceImage.size.height - faceRect.origin.y - 1));
return faceRect;
}
第三个,从一张图片上截取一部分图片
根据坐标信息,从一张大的图片上裁剪出我们需要的那一部分图片区域,具体如下:
/*
*在一张图片上根据坐标范围裁剪图片
*/
+ (UIImage *)cutImageWithRect:(CGRect)rect image:(UIImage *)cutImage;
+ (UIImage *)cutImageWithRect:(CGRect)rect image:(UIImage *)cutImage
{
CGImageRef cgRef = cutImage.CGImage;
CGImageRef imageRef = CGImageCreateWithImageInRect(cgRef, rect);
UIImage *thumbScale = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return thumbScale;
}
第四个,保存图片到本地
- (void)saveImageToPhotos:(UIImage*)savedImage
{
UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
NSString *msg = nil ;
if(error != NULL) msg = @"保存图片失败" ;
else msg = @"保存图片成功" ;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
message:msg
delegate:self
cancelButtonTitle:@"确定"
otherButtonTitles:nil];
[alert show];
}