Android
1. 需要权限
- <uses-permission Android:name="android.permission.READ_EXTERNAL_STORAGE"
- />
- <uses-permission Android:name="android.permission.WRITE_EXTERNAL_STORAGE"
- />
- // 保存文件到指定路径
- public static String saveImageToGallery(Context context, String bmpPath) {
- //
- File imgFile = new File(bmpPath);
- if (!imgFile.exists()) {
- return "fail";
- }
- // 插入图片到系统相册
- try {
- MediaStore.Images.Media.insertImage(context.getContentResolver(), bmpPath, "分享图片", "茶馆分享图片");
- // 保存图片后发送广播通知更新数据库
- Uri uri = Uri.parse(bmpPath);
- context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
- return "success";
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return "fail";
- }
iOS
1. 需要配置 iOS info.plist
- <key>
- NSPhotoLibraryAddUsageDescription
- </key>
- <string>
- 是否允许此 App 保存图片到相册?
- </string>
- <key>
- NSPhotoLibraryUsageDescription
- </key>
- <string>
- 此 App 需要您的同意才能读取媒体资料库
- </string>
2. 包含的头文件:
- #import <Photos/Photos.h>
- #import<AssetsLibrary/AssetsLibrary.h>
3. 包含相应的类库:
- Photos.framework
- AssetsLibrary.framework
- MODULE_METHOD_FUN(SysModule::saveImageToGallery)
- {
- _funcCB = func;
- char*p=(char*)args.data();
- NSString *nsMessage= [[NSString alloc] initWithCString:p encoding:NSUTF8StringEncoding];
- NSURL *url = [NSURL fileURLWithPath:nsMessage];
- __block NSString *assetId = nil;
- ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
- if (author ==kCLAuthorizationStatusRestricted || author ==kCLAuthorizationStatusDenied){
- // 无权限 引导去开启
- NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
- if ([[UIApplication sharedApplication] canOpenURL:url]) {
- [[UIApplication sharedApplication] openURL:url];
- }
- }else{
- // 1. 存储图片到 "相机胶卷"
- [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ // 这个 block 里保存一些 "修改" 性质的代码
- // 新建一个 PHAssetCreationRequest 对象, 保存图片到 "相机胶卷"
- // 返回 PHAsset(图片) 的字符串标识
- PHAssetChangeRequest *createAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:url];
- assetId = createAssetRequest.placeholderForCreatedAsset.localIdentifier;
- } completionHandler:^(BOOL success, NSError * _Nullable error) {
- if (error) {
- NSLog(@"保存图片到相机胶卷中失败");
- CallBack("fail","保存图片到相机胶卷中失败");
- }else{
- NSLog(@"成功保存图片到相机胶卷中");
- CallBack("success","成功保存图片到相机胶卷中");
- }
- }];
- }
- return "hasFunc";
- }
- ---------------------
来源: http://www.bubuko.com/infodetail-3035000.html