UIImage图片处理

#pragma mark 储存图片

- (void)saveImage:(UIImage *)image

{

//1) 储存到app的文件里,以image.png为名存到app home底下的Documents目录里

// 将照片保存到沙盒Documents目录中

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

// 保存照片的路径+名称:../Documents/image

NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"image.png"]];

filePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]stringByAppendingPathComponent:@"image.png"];// 方式二获取地址

[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES]; // 保存成功会返回YES

//2)储存到手机的图片库里

UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

}

#pragma mark 等比率缩放

- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize

{

UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));// 创建新的图片并制定大小

[image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];// 缩放画图

UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();//获取图片

UIGraphicsEndImageContext();// 关闭图形上下文

return scaledImage;

}

#pragma mark 自定长宽

- (UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize

{

UIGraphicsBeginImageContext(reSize);

[image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)];

UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return reSizeImage;

}

#pragma mark 根据给定得图片,从其指定区域截取一张新得图片

-(UIImage *)getImageFromImage:(UIImage *)image rect:(CGRect)rect

{

CGImageRef imageRef = image.CGImage;

CGImageRef subImageRef = CGImageCreateWithImageInRect(imageRef, rect);

UIGraphicsBeginImageContext(rect.size);

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextDrawImage(context, rect, subImageRef);

UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];

UIGraphicsEndImageContext();

return smallImage;

}

#pragma mark UIView转UIImage

- (UIImage *)createImageFromView:(UIView *)view

{

CGFloat scale = [UIScreen mainScreen].scale;// 屏幕密度

// 开始绘图,参数1:区域大小;参数2:是否是非透明的(如果需要显示半透明效果,需要传NO,否则传YES);参数3:屏幕密度

UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, scale);

[view.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();// 生成图片

UIGraphicsEndImageContext();// 关闭绘画通道

return image;

}

你可能感兴趣的:(UIImage图片处理)