Example #1
0
        /// <summary>
        /// MUST BE CALLED FROM THE UI THREAD
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="title"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task Show(string title, string message, string filePath)
        {
            string[]      str         = filePath.Split('/');
            PHFetchResult assetResult = PHAsset.FetchAssetsUsingLocalIdentifiers(str, null);
            PHAsset       asset       = assetResult.firstObject as PHAsset;
            Stream        stream      = null;

            PHImageManager.DefaultManager.RequestImageData(asset, null, async(data, dataUti, orientation, info) =>
            {
                UIImage newImage       = new UIImage(data);
                var items              = new NSObject[] { newImage };
                var activityController = new UIActivityViewController(items, null);
                var vc = GetVisibleViewController();

                NSString[] excludedActivityTypes = null;

                if (excludedActivityTypes != null && excludedActivityTypes.Length > 0)
                {
                    activityController.ExcludedActivityTypes = excludedActivityTypes;
                }

                if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
                {
                    if (activityController.PopoverPresentationController != null)
                    {
                        activityController.PopoverPresentationController.SourceView = vc.View;
                    }
                }

                await vc.PresentViewControllerAsync(activityController, true);
            });
        }
        void ImageEditor_ImageSaved(object sender, ImageSavedEventArgs e)
        {
            string[]      str         = e.Location.Split('/');
            PHFetchResult assetResult = PHAsset.FetchAssetsUsingLocalIdentifiers(str, null);
            PHAsset       asset       = assetResult.firstObject as PHAsset;
            Stream        stream      = null;

            PHImageManager.DefaultManager.RequestImageData(asset, null, async(data, dataUti, orientation, info) =>
            {
                UIImage newImage       = new UIImage(data);
                var items              = new NSObject[] { newImage };
                var activityController = new UIActivityViewController(items, null);


                NSString[] excludedActivityTypes = null;

                if (excludedActivityTypes != null && excludedActivityTypes.Length > 0)
                {
                    activityController.ExcludedActivityTypes = excludedActivityTypes;
                }

                if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
                {
                    if (activityController.PopoverPresentationController != null)
                    {
                        activityController.PopoverPresentationController.SourceView = presentController.View;
                    }
                }

                await presentController.PresentViewControllerAsync(activityController, true);
            });
        }
Example #3
0
        /// <summary>
        /// MUST BE CALLED FROM THE UI THREAD
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="title"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public void Show(string title, string message, string filePath)
        {
            string[]      str         = filePath.Split('/');
            PHFetchResult assetResult = PHAsset.FetchAssetsUsingLocalIdentifiers(str, null);
            PHAsset       asset       = assetResult.firstObject as PHAsset;

            PHImageManager.DefaultManager.RequestImageData(asset, null, HandlePHImageDataHandler);
        }
Example #4
0
        public async Task <GalleryImageXF> IF_SyncPhotoFromCloud(IGalleryPickerResultListener galleryPickerResultListener, GalleryImageXF imageSet, SyncPhotoOptions options)
        {
            try
            {
                bool FinishSync = false;

                Debug.WriteLine(imageSet.OriginalPath);

                var sortOptions = new PHFetchOptions();
                sortOptions.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("creationDate", false) };

                var FeechPhotoByIdentifiers = PHAsset.FetchAssetsUsingLocalIdentifiers(
                    new string[] { imageSet.OriginalPath },
                    sortOptions).Cast <PHAsset>().FirstOrDefault();

                if (FeechPhotoByIdentifiers != null)
                {
                    var requestOptions = new PHImageRequestOptions()
                    {
                        NetworkAccessAllowed = true,
                        DeliveryMode         = PHImageRequestOptionsDeliveryMode.HighQualityFormat,
                        ResizeMode           = PHImageRequestOptionsResizeMode.None,
                    };

                    var requestSize = new CoreGraphics.CGSize(options.Width, options.Height);
                    requestSize = PHImageManager.MaximumSize;

                    PHImageManager.DefaultManager.RequestImageForAsset(FeechPhotoByIdentifiers, requestSize, PHImageContentMode.AspectFit, requestOptions, (result, info) => {
                        if (result != null)
                        {
                            var newImage          = result.ResizeImage(options);
                            imageSet.ImageRawData = newImage.AsJPEG(options.Quality).ToArray();
                        }
                        FinishSync = true;
                    });

                    do
                    {
                        if (FinishSync)
                        {
                            return(imageSet);
                        }
                        await Task.Delay(1000);
                    } while (!FinishSync);
                }

                return(imageSet);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.StackTrace);
                return(imageSet);
            }
        }
        public static bool DeleteImagesFromGallery(string[] localIds)
        {
            var images  = PHAsset.FetchAssetsUsingLocalIdentifiers(localIds, new PHFetchOptions());
            var assets  = images.Select(a => (PHAsset)a).ToArray();
            var success = PHPhotoLibrary.SharedPhotoLibrary.PerformChangesAndWait
                          (
                () =>
            {
                PHAssetChangeRequest.DeleteAssets(assets);
            }, out var error
                          );

            if (error != null)
            {
                Console.WriteLine(error);
            }
            return(success);
        }
Example #6
0
        public void LoadSampleStream(string filename, SerializationModel model)
        {
            try
            {
                string[] str = filename.Split('/');

                PHFetchResult assetResult = PHAsset.FetchAssetsUsingLocalIdentifiers(str, null);
                PHAsset       asset       = assetResult.firstObject as PHAsset;
                Stream        stream      = new MemoryStream();
                PHImageManager.DefaultManager.RequestImageData(asset, null, (data, dataUti,
                                                                             orientation, info) =>
                {
                    byte[] byteArray = data.ToArray();
                    Stream streamm   = new MemoryStream(byteArray);
                    dictionary.Add(filename, streamm);
                    model.Location = filename;
                });
            }
            catch (Exception)
            {
            }
        }
        public async Task <string> CreatePreviewPath(string path, string type)
        {
            await Task.Delay(TimeSpan.FromMilliseconds(100));

            var fileName = System.IO.Path.GetFileNameWithoutExtension(path);
            var ext      = System.IO.Path.GetExtension(path);

            var strs        = path.Split('/');
            var assetResult = PHAsset.FetchAssetsUsingLocalIdentifiers(strs, null);
            var asset       = assetResult.firstObject as PHAsset;

            var thumbImageBytes =
                AssetImageService.GetImageBytes(asset, MediaFileGetImageOptions.CreateDefaultThumb());

            var thumbnailImagePath =
                MediaFileHelper.GetOutputPath(MediaFileType.Image, "TmpMedia",
                                              $"{fileName}-THUMBNAIL{ext}");

            System.IO.File.WriteAllBytes(thumbnailImagePath, thumbImageBytes);

            return(thumbnailImagePath);
        }
        void FinishCapture(object sender, Tuple <NSObject, NSError> e)
        {
            if (Element == null || Control == null)
            {
                return;
            }

            if (e.Item2 != null)
            {
                Element.RaiseMediaCaptureFailed(e.Item2.LocalizedDescription);
                return;
            }

            var photoData = e.Item1 as NSData;

            if (!Element.SavePhotoToFile && photoData != null)
            {
                var data = UIImage.LoadFromData(photoData).AsJPEG().ToArray();
                Device.BeginInvokeOnMainThread(() =>
                {
                    Element.RaiseMediaCaptured(new MediaCapturedEventArgs(imageData: data));
                });
                return;
            }

            PHObjectPlaceholder placeholder = null;

            PHPhotoLibrary.RequestAuthorization(status =>
            {
                if (status != PHAuthorizationStatus.Authorized)
                {
                    return;
                }

                // Save the captured file to the photo library.
                PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() =>
                {
                    var creationRequest = PHAssetCreationRequest.CreationRequestForAsset();
                    if (photoData != null)
                    {
                        creationRequest.AddResource(PHAssetResourceType.Photo, photoData, null);
                        placeholder = creationRequest.PlaceholderForCreatedAsset;
                    }
                    else if (e.Item1 is NSUrl outputFileUrl)
                    {
                        creationRequest.AddResource(
                            PHAssetResourceType.Video,
                            outputFileUrl,
                            new PHAssetResourceCreationOptions
                        {
                            ShouldMoveFile = true
                        });
                        placeholder = creationRequest.PlaceholderForCreatedAsset;
                    }
                }, (success2, error2) =>
                {
                    if (!success2)
                    {
                        Debug.WriteLine($"Could not save media to photo library: {error2}");
                        if (error2 != null)
                        {
                            Element.RaiseMediaCaptureFailed(error2.LocalizedDescription);
                            return;
                        }
                        Element.RaiseMediaCaptureFailed($"Could not save media to photo library");
                        return;
                    }

                    if (!(PHAsset.FetchAssetsUsingLocalIdentifiers(new[] { placeholder.LocalIdentifier }, null).firstObject is PHAsset asset))
                    {
                        Element.RaiseMediaCaptureFailed($"Could not save media to photo library");
                        return;
                    }
                    if (asset.MediaType == PHAssetMediaType.Image)
                    {
                        asset.RequestContentEditingInput(new PHContentEditingInputRequestOptions
                        {
                            CanHandleAdjustmentData = p => true
                        }, (input, info) =>
                        {
                            Device.BeginInvokeOnMainThread(() =>
                            {
                                Element.RaiseMediaCaptured(new MediaCapturedEventArgs(input.FullSizeImageUrl.Path));
                            });
                        });
                    }
                    else if (asset.MediaType == PHAssetMediaType.Video)
                    {
                        PHImageManager.DefaultManager.RequestAvAsset(asset, new PHVideoRequestOptions
                        {
                            Version = PHVideoRequestOptionsVersion.Original
                        }, (avAsset, mix, info) =>
                        {
                            if (!(avAsset is AVUrlAsset urlAsset))
                            {
                                Element.RaiseMediaCaptureFailed($"Could not save media to photo library");
                                return;
                            }
                            Device.BeginInvokeOnMainThread(() =>
                            {
                                Element.RaiseMediaCaptured(new MediaCapturedEventArgs(urlAsset.Url.Path));
                            });
                        });
                    }
                });
        public Task <SupportImageXF> IF_SyncPhotoFromCloud(SupportImageXF imageSet, SyncPhotoOptions options)
        {
            ManualResetEvent manualResetEvent = new ManualResetEvent(false);

            return(Task.Factory.StartNew(() => {
                try
                {
                    manualResetEvent.Reset();

                    var sortOptions = new PHFetchOptions();
                    sortOptions.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("creationDate", false) };

                    var FeechPhotoByIdentifiers = PHAsset.FetchAssetsUsingLocalIdentifiers(
                        new string[] { imageSet.OriginalPath },
                        sortOptions).Cast <PHAsset>().FirstOrDefault();

                    Console.WriteLine(imageSet.OriginalPath + "  ==> Run at step 1");

                    if (FeechPhotoByIdentifiers != null)
                    {
                        var requestOptions = new PHImageRequestOptions()
                        {
                            NetworkAccessAllowed = true,
                            DeliveryMode = PHImageRequestOptionsDeliveryMode.HighQualityFormat,
                            ResizeMode = PHImageRequestOptionsResizeMode.None,
                        };

                        var requestSize = PHImageManager.MaximumSize;

                        Console.WriteLine(imageSet.OriginalPath + "  ==> Run at step 2");

                        PHImageManager.DefaultManager.RequestImageForAsset(FeechPhotoByIdentifiers, requestSize, PHImageContentMode.AspectFit, requestOptions, (image, info) => {
                            Console.WriteLine(imageSet.OriginalPath + "  ==> Run at step 3");
                            if (image != null)
                            {
                                //var newImage = result.ResizeImage(options);
                                //imageSet.ImageRawData = newImage.AsJPEG(options.Quality).ToArray();
                                try
                                {
                                    var url = info.ObjectForKey(new NSString("PHImageFileURLKey")) as NSUrl;
                                    if (url == null)
                                    {
                                        // Get image and save to file
                                        var filePath = Path.Combine(Path.GetTempPath(), $"Photo_{Path.GetTempFileName()}");
                                        image.AsJPEG().Save(filePath, false, out _);
                                        url = new NSUrl(filePath);
                                    }

                                    var fileName = url.Path;
                                    var newWidth = image.Size.Width;
                                    var newHeight = image.Size.Height;

                                    // Create temp file path
                                    var fileNameOnly = Path.GetFileNameWithoutExtension(fileName);
                                    var fileExtension = Path.GetExtension(fileName);
                                    var newFileName = fileNameOnly + "_" + DateTime.Now.ToFormatString("yyyyMMddHHmmss") + "_" + newWidth + "x" + newHeight + fileExtension;
                                    var tempPath = Path.Combine(Path.GetTempPath(), newFileName);
                                    FileHelper.CreateFile(tempPath);

                                    // Write data to temp file
                                    using (var newStream = FileHelper.GetWriteFileStream(tempPath))
                                    {
                                        using (var imageData = image.AsJPEG())
                                        {
                                            var buffer = new byte[imageData.Length];
                                            System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, buffer, 0, Convert.ToInt32(imageData.Length));
                                            newStream.Write(buffer, 0, buffer.Length);

                                            imageSet.ProcessFilePath = tempPath;
                                            //Console.WriteLine("Finish item at ==> " + tempPath);
                                        }
                                    }
                                    Console.WriteLine(imageSet.OriginalPath + "  ==> Run at step 4");
                                    manualResetEvent.Set();
                                }
                                catch (Exception ex)
                                {
                                    // Ignore
                                    Console.WriteLine("Error for " + imageSet.OriginalPath);
                                    Console.WriteLine(ex.StackTrace);
                                    manualResetEvent.Set();
                                }
                            }
                            else
                            {
                                Console.WriteLine("Can not sync image");
                                manualResetEvent.Set();
                            }
                        });
                    }
                    else
                    {
                        Console.WriteLine(imageSet.OriginalPath + "  ==> Run at step 5");
                        manualResetEvent.Set();
                    }

                    manualResetEvent.WaitOne();

                    return imageSet;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    return imageSet;
                }
            }));
        }
Example #10
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));
        }
Example #11
0
        public void Refresh()
        {
            Version = 1;

            if (Asset == null && !string.IsNullOrEmpty(Id))
            {
                Asset = PHAsset.FetchAssetsUsingLocalIdentifiers(new[] { Id }, null).OfType <PHAsset>().FirstOrDefault();
                if (Asset == null)
                {
                    IsAvailable = false;
                    return;
                }

                if (Type != (PLAssetType)Asset.MediaType)
                {
                    HasChanged = true;
                }
                Type = (PLAssetType)Asset.MediaType;

                if (Tags != (PLAssetTags)Asset.MediaSubtypes)
                {
                    HasChanged = true;
                }
                Tags = (PLAssetTags)Asset.MediaSubtypes;

                var creation = Asset.CreationDate.ToDateTime();
                if (creation != CreationDate)
                {
                    HasChanged = true;
                }
                CreationDate = creation;

                var modification = Asset.ModificationDate.ToDateTime();
                if (modification != ModificationDate)
                {
                    HasChanged = true;
                }
                ModificationDate = modification;

                RefreshResources();
                Size = Resources?.Sum(x => x.UserInfoGetSize() ?? 0) ?? 0;

                return;
            }

            if (Id == null && Asset != null)
            {
                IsAvailable = true;

                Id               = Asset.LocalIdentifier;
                Type             = (PLAssetType)Asset.MediaType;
                Tags             = (PLAssetTags)Asset.MediaSubtypes;
                CreationDate     = Asset.CreationDate.ToDateTime();
                ModificationDate = Asset.ModificationDate.ToDateTime();

                if (Resources == null || FileName == null)
                {
                    RefreshResources();
                }
                if (Size == 0)
                {
                    Size = Resources?.Sum(x => x.UserInfoGetSize() ?? 0) ?? 0;
                }

                return;
            }

            IsAvailable = false;
        }