iOS 把图片保存到相册,并获取图片文件名

本文介绍了一种在iOS应用中将图片保存到用户相册的方法,并提供了两种实现方案:一种使用系统的UIImageWriteToSavedPhotosAlbum方法,另一种通过ALAssetsLibrary进行更深入的交互并获取保存图片的文件名。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];

    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {

        UIImageWriteToSavedPhotosAlbum(image,self,@selector(image:didFinishSavingWithError:contextInfo:),NULL);

    }

}

- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo

{

    if (error) {

        DLog(@"图片保存失败!");

    }else{

        DLog(@"图片保存成功!");

    }

}

此方法可以把其他来源的图片也可保存到相册



 //image从相机中获取的时候存入相册中

    //保存方法1

//        UIImageWriteToSavedPhotosAlbum(img.image,self,@selector(image:didFinishSavingWithError:contextInfo:),NULL);

//         imageData = nil;

        

        WEAKSELF

        //保存方法2同时获取保存的相片文件名

        __blockALAssetsLibrary *lib = [[ALAssetsLibraryalloc] init];

        [lib writeImageToSavedPhotosAlbum:img.image.CGImagemetadata:nilcompletionBlock:^(NSURL *assetURL,NSError *error) {

            

            ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)

            {

                ALAssetRepresentation *imageRep = [imageAssetdefaultRepresentation];

                weakSelf.imageName = [NSStringstringWithFormat:@"%@",[imageRepfilename]];

                NSLog(@"[imageRep filename 1] : %@", [imageRepfilename]);

                DBLog(@"self.addressImageName照相0 = %@",weakSelf.imageName);

                commitBlock(img.image,UIImageJPEGRepresentation(img.image,0.5),self.imageName);

            };

            ALAssetsLibrary* assetslibrary = [[ALAssetsLibraryalloc] init];

            [assetslibrary assetForURL:assetURLresultBlock:resultblock failureBlock:nil];

            

            NSLog(@"assetURL = %@, error = %@", assetURL, error);

            lib = nil;

            

        }];

        

    }];





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值