Пример #1
0
        partial void AddAsset(NSObject sender)
        {
            var rnd = new Random();

            // Create a random dummy image.
            var size = (rnd.Next(0, 2) == 0)
                                ? new CGSize(400f, 300f)
                                : new CGSize(300f, 400f);

            var renderer = new UIGraphicsImageRenderer(size);
            var image    = renderer.CreateImage(context => {
                UIColor.FromHSBA((float)rnd.NextDouble(), 1, 1, 1).SetFill();
                context.FillRect(context.Format.Bounds);
            });

            // Add it to the photo library
            PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => {
                PHAssetChangeRequest creationRequest = PHAssetChangeRequest.FromImage(image);

                if (AssetCollection != null)
                {
                    var addAssetRequest = PHAssetCollectionChangeRequest.ChangeRequest(AssetCollection);
                    addAssetRequest.AddAssets(new PHObject [] {
                        creationRequest.PlaceholderForCreatedAsset
                    });
                }
            }, (success, error) => {
                if (!success)
                {
                    Console.WriteLine(error.LocalizedDescription);
                }
            });
        }
Пример #2
0
        partial void RemoveAsset(NSObject sender)
        {
            Action <bool, NSError> completion = (success, error) => {
                if (success)
                {
                    PHPhotoLibrary.SharedPhotoLibrary.UnregisterChangeObserver(this);
                    DispatchQueue.MainQueue.DispatchSync(() => NavigationController.PopViewController(true));
                }
                else
                {
                    Console.WriteLine($"can't remove asset: {error.LocalizedDescription}");
                }
            };

            if (AssetCollection != null)
            {
                // Remove asset from album
                PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => {
                    var request = PHAssetCollectionChangeRequest.ChangeRequest(AssetCollection);
                    request.RemoveAssets(new PHObject [] { Asset });
                }, completion);
            }
            else
            {
                // Delete asset from library
                PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() =>
                                                                 PHAssetChangeRequest.DeleteAssets(new [] { Asset }), completion);
            }
        }
Пример #3
0
        public static bool SaveImageToGalery(string imagePath, string albumName)
        {
            var saved = true;
            PHAssetCollection customAlbum = null;

            if (!string.IsNullOrEmpty(albumName))
            {
                customAlbum = FindOrCreateAlbum(albumName);
                if (customAlbum == null)
                {
                    return(false);
                }
            }

            PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(
                () =>
            {
                var assetRequest = PHAssetChangeRequest.FromImage(NSUrl.FromFilename(imagePath));
                if (customAlbum != null)
                {
                    var albumRequest = PHAssetCollectionChangeRequest.ChangeRequest(customAlbum);
                    albumRequest?.AddAssets(new[] { assetRequest.PlaceholderForCreatedAsset });
                }
            },
                (success, error) =>
            {
                if (!success)
                {
                    Console.WriteLine(error);
                    saved = success;
                }
            }
                );
            return(saved);
        }
Пример #4
0
        void SaveToAlbum(string watermarkedPath)
        {
            var lib = PHPhotoLibrary.SharedPhotoLibrary;

            lib.PerformChanges(() =>
            {
                var album             = PHAssetCollection.FetchAssetCollections(new[] { Xamarin.Essentials.Preferences.Get("iOSAlbumIdentifier", string.Empty) }, null)?.firstObject as PHAssetCollection;
                var collectionRequest = PHAssetCollectionChangeRequest.ChangeRequest(album);

                if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
                {
                    var options = new PHAssetResourceCreationOptions
                    {
                        ShouldMoveFile = true
                    };
                    var changeRequest = PHAssetCreationRequest.CreationRequestForAsset();
                    changeRequest.AddResource(PHAssetResourceType.Video, NSUrl.FromString(watermarkedPath), options);

                    collectionRequest.AddAssets(new[] { changeRequest.PlaceholderForCreatedAsset });
                }
                else
                {
                    var changeRequest2 = PHAssetChangeRequest.FromVideo(NSUrl.FromString(watermarkedPath));
                    collectionRequest.AddAssets(new[] { changeRequest2.PlaceholderForCreatedAsset });
                }

                RetrieveLastAssetSaved();
            }, (success, err) =>
            {
            });
        }
        partial void TrashButtonClickHandler(NSObject sender)
        {
            Action <bool, NSError> completionHandler = (success, error) => {
                if (success)
                {
                    DispatchQueue.MainQueue.DispatchAsync(() =>
                                                          NavigationController.PopViewController(true)
                                                          );
                }
                else
                {
                    Console.WriteLine(error.LocalizedDescription);
                }
            };

            if (AssetCollection != null)
            {
                // Remove asset from album
                PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => {
                    var changeRequest = PHAssetCollectionChangeRequest.ChangeRequest(AssetCollection);
                    changeRequest.RemoveAssets(new PHObject[] { Asset });
                }, completionHandler);
            }
            else
            {
                // Delete asset from library
                PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() =>
                                                                 PHAssetChangeRequest.DeleteAssets(new [] { Asset }), completionHandler);
            }
        }
        partial void AddButtonClickHandler(NSObject sender)
        {
            // Create a random dummy image.
            var rect = new Random().Next(0, 2) == 0 ?
                       new CGRect(0f, 0f, 400f, 300f) : new CGRect(0f, 0f, 300f, 400f);

            UIGraphics.BeginImageContextWithOptions(rect.Size, false, 1f);
            UIColor.FromHSBA(new Random().Next(0, 100) / 100f, 1f, 1f, 1f).SetFill();
            UIGraphics.RectFillUsingBlendMode(rect, CGBlendMode.Normal);
            UIImage image = UIGraphics.GetImageFromCurrentImageContext();

            UIGraphics.EndImageContext();

            // Add it to the photo library
            PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => {
                PHAssetChangeRequest assetChangeRequest = PHAssetChangeRequest.FromImage(image);

                if (AssetCollection != null)
                {
                    PHAssetCollectionChangeRequest assetCollectionChangeRequest = PHAssetCollectionChangeRequest.ChangeRequest(AssetCollection);
                    assetCollectionChangeRequest.AddAssets(new PHObject[] {
                        assetChangeRequest.PlaceholderForCreatedAsset
                    });
                }
            }, (success, error) => {
                if (!success)
                {
                    Console.WriteLine(error.LocalizedDescription);
                }
            });
        }
Пример #7
0
        public static bool SaveVideoToGalery(NSUrl video, string path, string albumName)
        {
            var saved       = true;
            var compatible  = UIVideo.IsCompatibleWithSavedPhotosAlbum(path);
            var customAlbum = string.IsNullOrEmpty(albumName) ? null : FindOrCreateAlbum(albumName);

            if (!compatible)
            {
                return(false);
            }
            UIVideo.SaveToPhotosAlbum(path, (path, error) =>
            {
                if (error != null)
                {
                    saved = false;
                    Console.WriteLine(error);
                }
                else if (customAlbum != null)
                {
                    var savedAsset = (PHAsset)PHAsset.FetchAssets(PHAssetMediaType.Video,
                                                                  new PHFetchOptions
                    {
                        SortDescriptors = new[] { new NSSortDescriptor("creationDate", false) },
                        FetchLimit      = 1
                    }).FirstOrDefault();
                    if (savedAsset != null)
                    {
                        PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() =>
                        {
                            var albumRequest = PHAssetCollectionChangeRequest.ChangeRequest(customAlbum);
                            albumRequest?.AddAssets(new[] { savedAsset });
                        },
                                                                         (success, error) =>
                        {
                            if (!success)
                            {
                                Console.WriteLine(error);
                                saved = success;
                            }
                        }
                                                                         );
                    }
                }
            });

            return(saved);
        }
Пример #8
0
        public static async Task <bool> SaveToLibrary(string path, string albumName)
        {
            var source = new TaskCompletionSource <bool>();
            PHAssetCollection album = await GetAlbum(albumName);

            PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() =>
            {
                var assetReq    = PHAssetChangeRequest.FromImage(NSUrl.CreateFileUrl(path, null));
                var albumReq    = PHAssetCollectionChangeRequest.ChangeRequest(album);
                var placeholder = assetReq.PlaceholderForCreatedAsset;
                albumReq.AddAssets(new[] { (PHObject)placeholder });
            }, (success, err) =>
            {
                Debug.WriteLine($"SaveToLibrary: {success}");
                source.SetResult(success);
            });
            return(await source.Task);
        }
Пример #9
0
        public async Task <string> ImageSave(MemoryStream stream, bool compatibleMode, string fileName = null)
        {
            NSError error = null;

            //虽然对于iOS没有这两个权限,但要保证方法异步,所以还是保留下来了
            await Permissions.RequestAsync <Permissions.StorageWrite>();

            await Permissions.RequestAsync <Permissions.StorageRead>();

            //判断相册是否存在,不存在就创建
            PHAssetCollection appAlbum = null;
            PHFetchResult     albums   = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, null);

            foreach (PHAssetCollection album in albums)
            {
                if (album.LocalizedTitle == albumName)
                {
                    appAlbum = album;
                }
            }
            if (appAlbum == null)   //相册不存在,新建
            {
                string[] albumID = new string[1];
                PHPhotoLibrary.SharedPhotoLibrary.PerformChangesAndWait(() =>
                {
                    albumID[0] = PHAssetCollectionChangeRequest.CreateAssetCollection(albumName).PlaceholderForCreatedAssetCollection.LocalIdentifier;
                }, out error);
                appAlbum = PHAssetCollection.FetchAssetCollections(albumID, null)[0] as PHAssetCollection;
            }

            //获取路径及名称
            string documentsPath;

            documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            if (fileName == null || fileName == "")
            {
                fileName = "Tank_" + DateTime.Now.ToLocalTime().ToString("yyyyMMdd_HHmmss") + ".png";
            }
            string path = Path.Combine(documentsPath, fileName);

            //保存
            FileStream photoTankFile = new FileStream(path, FileMode.Create);

            byte[] photoTank = stream.ToArray();
            photoTankFile.Write(photoTank, 0, photoTank.Length);
            photoTankFile.Flush();
            photoTankFile.Close();

            //如果是图片或视频,就添加到相册里
            string MimeType = MimeUtility.GetMimeMapping(path);

            if (MimeType.IndexOf("image") != -1 || MimeType.IndexOf("video") != -1)
            {
                string[] assetID = new string[1];
                PHPhotoLibrary.SharedPhotoLibrary.PerformChangesAndWait(() =>
                {
                    if (MimeType.IndexOf("image") != -1)
                    {
                        assetID[0] = PHAssetChangeRequest.FromImage(new NSUrl(path, true)).PlaceholderForCreatedAsset.LocalIdentifier;
                    }
                    if (MimeType.IndexOf("video") != -1)
                    {
                        assetID[0] = PHAssetChangeRequest.FromVideo(new NSUrl(path, true)).PlaceholderForCreatedAsset.LocalIdentifier;
                    }
                }, out error);
                PHAsset    asset = PHAsset.FetchAssetsUsingLocalIdentifiers(assetID, null)[0] as PHAsset;
                PHObject[] objs  = { asset };
                PHPhotoLibrary.SharedPhotoLibrary.PerformChangesAndWait(() =>
                {
                    PHAssetCollectionChangeRequest collectionChangeRequest = PHAssetCollectionChangeRequest.ChangeRequest(appAlbum);
                    collectionChangeRequest.InsertAssets(objs, new NSIndexSet(0));
                }, out error);
            }

            return(Path.Combine(fileName));
        }