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

iOS 图片 保存到沙盒路径/相册、图片缩小、图片截取

2017-03-03 11:00 253 查看
//截取图片(截取图片的位置是根据原图的大小,而不是UIImageView的大小)
-(UIImage *)cutOutImageWithImage:(UIImage*)image  WithRect:(CGRect)rect{
    CGImageRef imageRef = image.CGImage;
    imageRef = CGImageCreateWithImageInRect(imageRef, rect);
    UIImage *newImage = [UIImage
imageWithCGImage:imageRef];
    return newImage;
}
//将原图片缩小
而不是将ImageView 缩小
-(UIImage *)compressImageWithImage:(UIImage *)image scaledToSize:(CGSize)size{
    //创建图片上下文
    UIGraphicsBeginImageContext(size);
    //告诉旧图片按新的尺寸画在这个新的上下文上
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    //从新的上下文上获得新图片
    UIImage *newImage =
UIGraphicsGetImageFromCurrentImageContext();
    //结束上下文
    UIGraphicsEndImageContext();
    return newImage;
}

//将图片保存到相册
使用UIImageWriteToSavedPhotosAlbum函数将图片保存到相册
/*
 第一个参数是要保存到相册的图片对象
 
 第二个参数是保存完成后回调的目标对象
 
 第三个参数就是保存完成后回调到目标对象的哪个方法中,方法的声明要如代码中所示的:
 
 */

- (void)saveImageToPhotoAlbum:(UIImage *)image
{
    UIImageWriteToSavedPhotosAlbum(image,
self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge
void *)self);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void
*)contextInfo
{
    
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}

//将图片保存到本地沙盒路径下
-(void)saveImageDocumentsWithImageName:(NSString *)imageName andImage:(UIImage *)image{
    //拿到图片
    UIImage *imagesave = image;
    NSString *path_sandox =
NSHomeDirectory();
    //设置一个图片的存储路径
    NSString *imagePath = [NSString
stringWithFormat:@"%@/Documents/%@",path_sandox,imageName];
    //把图片直接保存到指定的路径(同时应该把图片的路径imagePath存起来,下次就可以直接用来取)
    [UIImagePNGRepresentation(imagesave)
writeToFile:imagePath atomically:YES];
}

// 读取并存贮到相册
-(UIImage *)getDocumentImageWithImageName:(NSString *)imageName{
    // 读取沙盒路径图片
    NSString *path=[NSString
stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(),imageName];
    // 拿到沙盒路径图片
    UIImage *imgFromUrl3=[[UIImage
alloc]initWithContentsOfFile:path];
    return imgFromUrl3;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: