Exemplo n.º 1
0
        private async Task<MediaFile> GetMovieMediaFile(NSDictionary info)
        {
            var url = (NSUrl)info[UIImagePickerController.MediaURL];

            var path = GetOutputPath(MediaImplementation.TypeMovie,
                      options.Directory ?? ((IsCaptured) ? string.Empty : "temp"),
                      options.Name ?? Path.GetFileName(url.Path));

            try
            {
                File.Move(url.Path, path);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Unable to move file, trying to copy. {ex.Message}");
                try
                {
                    File.Copy(url.Path, path);
                    File.Delete(url.Path);
                }
                catch (Exception)
                {
                    Console.WriteLine($"Unable to copy/delete file, will be left around :( {ex.Message}");
                }
            }

            string aPath = path;
            if (source != UIImagePickerControllerSourceType.Camera)
            {
                //try to get the album path's url
                var url2 = (NSUrl)info[UIImagePickerController.ReferenceUrl];
                aPath = url2?.AbsoluteString;
            }
            else
            {
                if (options.SaveToAlbum)
				{
					PhotoLibraryAccess.SaveVideoToGalery(url, path, options.Directory);
				}
			}

            var asset = AVAsset.FromUrl(new NSUrl($"file://{path}"));
            var duration = asset.Duration.Seconds;

            return new MediaFile(path, () => File.OpenRead(path), albumPath: aPath)
            {
                Type = MediaType.Video,
                Duration = duration,
            };
        }
Exemplo n.º 2
0
		private (string, NSDictionary) GetImageMetadata(NSDictionary info)
		{
			string localId = null;
			NSDictionary meta = null;
			try
			{
				if (source == UIImagePickerControllerSourceType.Camera)
				{
					meta = info[UIImagePickerController.MediaMetadata] as NSDictionary;
					if (meta != null && meta.ContainsKey(ImageIO.CGImageProperties.Orientation))
					{
						var newMeta = new NSMutableDictionary();
						newMeta.SetValuesForKeysWithDictionary(meta);
						var newTiffDict = new NSMutableDictionary();
						newTiffDict.SetValuesForKeysWithDictionary(meta[ImageIO.CGImageProperties.TIFFDictionary] as NSDictionary);
						newTiffDict.SetValueForKey(meta[ImageIO.CGImageProperties.Orientation], ImageIO.CGImageProperties.TIFFOrientation);
						newMeta[ImageIO.CGImageProperties.TIFFDictionary] = newTiffDict;

						meta = newMeta;
					}
					var location = options.Location;
					if (meta != null && location != null)
					{
						meta = SetGpsLocation(meta, location);
					}
				}
				else
				{
					(meta, localId) = PhotoLibraryAccess.GetPhotoLibraryMetadata(info[UIImagePickerController.ReferenceUrl] as NSUrl);
				}
				if (options.RotateImage)
				{
					meta.SetValueForKey((NSNumber)0, ImageIO.CGImageProperties.Orientation);
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine($"Unable to get metadata: {ex}");
			}
			return (localId, meta);
		}
        private async Task <MediaFile> GetPictureMediaFile(NSDictionary info)
        {
            var image = (UIImage)info[UIImagePickerController.EditedImage] ?? (UIImage)info[UIImagePickerController.OriginalImage];

            if (image == null)
            {
                return(null);
            }

            var path = GetOutputPath(MediaImplementation.TypeImage,
                                     options.Directory ?? ((IsCaptured) ? string.Empty : "temp"),
                                     options.Name);

            var cgImage = image.CGImage;

            var   percent   = 1.0f;
            float newHeight = image.CGImage.Height;
            float newWidth  = image.CGImage.Width;

            if (options.PhotoSize != PhotoSize.Full)
            {
                try
                {
                    switch (options.PhotoSize)
                    {
                    case PhotoSize.Large:
                        percent = .75f;
                        break;

                    case PhotoSize.Medium:
                        percent = .5f;
                        break;

                    case PhotoSize.Small:
                        percent = .25f;
                        break;

                    case PhotoSize.Custom:
                        percent = (float)options.CustomPhotoSize / 100f;
                        break;
                    }

                    if (options.PhotoSize == PhotoSize.MaxWidthHeight && options.MaxWidthHeight.HasValue)
                    {
                        var max = Math.Max(image.CGImage.Width, image.CGImage.Height);
                        if (max > options.MaxWidthHeight.Value)
                        {
                            percent = (float)options.MaxWidthHeight.Value / (float)max;
                        }
                    }

                    if (percent < 1.0f)
                    {
                        //begin resizing image
                        image = image.ResizeImageWithAspectRatio(percent);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Unable to compress image: {ex}");
                }
            }


            NSDictionary meta = null;

            try
            {
                if (options.SaveMetaData)
                {
                    if (source == UIImagePickerControllerSourceType.Camera)
                    {
                        meta = info[UIImagePickerController.MediaMetadata] as NSDictionary;
                        if (meta != null && meta.ContainsKey(ImageIO.CGImageProperties.Orientation))
                        {
                            var newMeta = new NSMutableDictionary();
                            newMeta.SetValuesForKeysWithDictionary(meta);
                            var newTiffDict = new NSMutableDictionary();
                            newTiffDict.SetValuesForKeysWithDictionary(meta[ImageIO.CGImageProperties.TIFFDictionary] as NSDictionary);
                            newTiffDict.SetValueForKey(meta[ImageIO.CGImageProperties.Orientation], ImageIO.CGImageProperties.TIFFOrientation);
                            newMeta[ImageIO.CGImageProperties.TIFFDictionary] = newTiffDict;

                            meta = newMeta;
                        }
                        var location = options.Location;
                        if (meta != null && location != null)
                        {
                            meta = SetGpsLocation(meta, location);
                        }
                    }
                    else
                    {
                        meta = PhotoLibraryAccess.GetPhotoLibraryMetadata(info[UIImagePickerController.ReferenceUrl] as NSUrl);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Unable to get metadata: {ex}");
            }

            //iOS quality is 0.0-1.0
            var quality    = (options.CompressionQuality / 100f);
            var savedImage = false;

            if (meta != null)
            {
                savedImage = SaveImageWithMetadata(image, quality, meta, path);
            }

            if (!savedImage)
            {
                var finalQuality = quality;
                var imageData    = image.AsJPEG(finalQuality);

                //continue to move down quality , rare instances
                while (imageData == null && finalQuality > 0)
                {
                    finalQuality -= 0.05f;
                    imageData     = image.AsJPEG(finalQuality);
                }

                if (imageData == null)
                {
                    throw new NullReferenceException("Unable to convert image to jpeg, please ensure file exists or lower quality level");
                }


                imageData.Save(path, true);
                imageData.Dispose();
            }


            string aPath = null;

            if (source != UIImagePickerControllerSourceType.Camera)
            {
                //try to get the album path's url
                var url = (NSUrl)info[UIImagePickerController.ReferenceUrl];
                aPath = url?.AbsoluteString;
            }
            else
            {
                if (options.SaveToAlbum)
                {
                    try
                    {
                        var library   = new ALAssetsLibrary();
                        var albumSave = await library.WriteImageToSavedPhotosAlbumAsync(cgImage, meta);

                        aPath = albumSave.AbsoluteString;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("unable to save to album:" + ex);
                    }
                }
            }

            Func <Stream> getStreamForExternalStorage = () =>
            {
                if (options.RotateImage)
                {
                    return(RotateImage(image));
                }
                else
                {
                    return(File.OpenRead(path));
                }
            };

            return(new MediaFile(path, () => File.OpenRead(path), streamGetterForExternalStorage: () => getStreamForExternalStorage(), albumPath: aPath));
        }
Exemplo n.º 4
0
 public bool RemoveMediaFromGallery(string[] ids) => PhotoLibraryAccess.DeleteImagesFromGallery(ids);
Exemplo n.º 5
0
        private async Task <MediaFile> GetPictureMediaFile(NSDictionary info)
        {
            var image = (UIImage)info[UIImagePickerController.EditedImage] ?? (UIImage)info[UIImagePickerController.OriginalImage];

            NSDictionary meta = null;

            if (source == UIImagePickerControllerSourceType.Camera)
            {
                meta = info[UIImagePickerController.MediaMetadata] as NSDictionary;
                if (meta != null && meta.ContainsKey(ImageIO.CGImageProperties.Orientation))
                {
                    var newMeta = new NSMutableDictionary();
                    newMeta.SetValuesForKeysWithDictionary(meta);
                    var newTiffDict = new NSMutableDictionary();
                    newTiffDict.SetValuesForKeysWithDictionary(meta[ImageIO.CGImageProperties.TIFFDictionary] as NSDictionary);
                    newTiffDict.SetValueForKey(meta[ImageIO.CGImageProperties.Orientation], ImageIO.CGImageProperties.TIFFOrientation);
                    newMeta[ImageIO.CGImageProperties.TIFFDictionary] = newTiffDict;
                    meta = newMeta;
                }
                var location = options.Location;
                if (meta != null && location.Latitude > 0.0)
                {
                    meta = SetGpsLocation(meta, location);
                }
            }
            else
            {
                meta = PhotoLibraryAccess.GetPhotoLibraryMetadata(info[UIImagePickerController.ReferenceUrl] as NSUrl);
            }

            string path = GetOutputPath(MediaImplementation.TypeImage,
                                        options.Directory ?? ((IsCaptured) ? String.Empty : "temp"),
                                        options.Name);

            var cgImage = image.CGImage;

            if (options.PhotoSize != PhotoSize.Full)
            {
                try
                {
                    var percent = 1.0f;
                    switch (options.PhotoSize)
                    {
                    case PhotoSize.Large:
                        percent = .75f;
                        break;

                    case PhotoSize.Medium:
                        percent = .5f;
                        break;

                    case PhotoSize.Small:
                        percent = .25f;
                        break;

                    case PhotoSize.Custom:
                        percent = (float)options.CustomPhotoSize / 100f;
                        break;
                    }

                    if (options.PhotoSize == PhotoSize.MaxWidthHeight && options.MaxWidthHeight.HasValue)
                    {
                        var max = Math.Max(image.CGImage.Width, image.CGImage.Height);
                        if (max > options.MaxWidthHeight)
                        {
                            percent = (float)options.MaxWidthHeight / (float)max;
                        }
                    }

                    //calculate new size
                    var width  = (image.CGImage.Width * percent);
                    var height = (image.CGImage.Height * percent);

                    //begin resizing image
                    image = image.ResizeImageWithAspectRatio(width, height);
                    //update exif pixel dimiensions
                    meta[ImageIO.CGImageProperties.ExifDictionary].SetValueForKey(new NSString(width.ToString()), ImageIO.CGImageProperties.ExifPixelXDimension);
                    meta[ImageIO.CGImageProperties.ExifDictionary].SetValueForKey(new NSString(height.ToString()), ImageIO.CGImageProperties.ExifPixelYDimension);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Unable to compress image: {ex}");
                }
            }

            //iOS quality is 0.0-1.0
            var quality = (options.CompressionQuality / 100f);

            if (meta == null)
            {
                image.AsJPEG(quality).Save(path, true);
            }
            else
            {
                var success = SaveImageWithMetadata(image, quality, meta, path);
                if (!success)
                {
                    image.AsJPEG(quality).Save(path, true);
                }
            }

            string aPath = null;

            if (source != UIImagePickerControllerSourceType.Camera)
            {
                //try to get the album path's url
                var url = (NSUrl)info[UIImagePickerController.ReferenceUrl];
                aPath = url?.AbsoluteString;
            }
            else
            {
                if (this.options.SaveToAlbum)
                {
                    try
                    {
                        var library   = new ALAssetsLibrary();
                        var albumSave = await library.WriteImageToSavedPhotosAlbumAsync(cgImage, meta);

                        aPath = albumSave.AbsoluteString;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("unable to save to album:" + ex);
                    }
                }
            }

            return(new MediaFile(path, () => File.OpenRead(path), albumPath: aPath));
        }
        static void ResizeAndCompressImage(StoreCameraMediaOptions options, MediaFile mediaFile, string pathExtension)
        {
            var image   = UIImage.FromFile(mediaFile.Path);
            var percent = 1.0f;

            if (options.PhotoSize != PhotoSize.Full)
            {
                try
                {
                    switch (options.PhotoSize)
                    {
                    case PhotoSize.Large:
                        percent = .75f;
                        break;

                    case PhotoSize.Medium:
                        percent = .5f;
                        break;

                    case PhotoSize.Small:
                        percent = .25f;
                        break;

                    case PhotoSize.Custom:
                        percent = (float)options.CustomPhotoSize / 100f;
                        break;
                    }

                    if (options.PhotoSize == PhotoSize.MaxWidthHeight && options.MaxWidthHeight.HasValue)
                    {
                        var max = Math.Max(image.Size.Width, image.Size.Height);
                        if (max > options.MaxWidthHeight.Value)
                        {
                            percent = (float)options.MaxWidthHeight.Value / (float)max;
                        }
                    }

                    if (percent < 1.0f)
                    {
                        //begin resizing image
                        image = image.ResizeImageWithAspectRatio(percent);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Unable to compress image: {ex}");
                }
            }
            NSDictionary meta = null;

            if (options.SaveMetaData)
            {
                try
                {
                    meta = PhotoLibraryAccess.GetPhotoLibraryMetadata(new NSUrl(mediaFile.AlbumPath));
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Unable to get metadata: {ex}");
                }
            }
            //iOS quality is 0.0-1.0
            var quality    = (options.CompressionQuality / 100f);
            var savedImage = false;

            if (meta != null)
            {
                savedImage = MediaPickerDelegate.SaveImageWithMetadata(image, quality, meta, mediaFile.Path, pathExtension);
            }

            if (!savedImage)
            {
                if (pathExtension == "png")
                {
                    image.AsPNG().Save(mediaFile.Path, true);
                }
                else
                {
                    image.AsJPEG(quality).Save(mediaFile.Path, true);
                }
            }

            image?.Dispose();
            image = null;
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
        }
Exemplo n.º 7
0
        private async Task<MediaFile> GetPictureMediaFile(NSDictionary info)
		{
			var image = (UIImage)info[UIImagePickerController.EditedImage] ?? (UIImage)info[UIImagePickerController.OriginalImage];
			if (image == null)
				return null;

			// If rotate image option, then rotate the image to the original orientation it was taken
			// instead of the orientation apple saves it to storage as with the orientation as metadata.
			if (options.RotateImage)
			{
				image = RotateImage(image);
			}

			var path = GetOutputPath(MediaImplementation.TypeImage,
				options.Directory ?? ((IsCaptured) ? string.Empty : "temp"),
				options.Name);

			var cgImage = image.CGImage;

			var percent = 1.0f;
			float newHeight = image.CGImage.Height;
			float newWidth = image.CGImage.Width;

			if (options.PhotoSize != PhotoSize.Full)
			{
				try
				{
					percent = options.PhotoSize switch
					{
						PhotoSize.Large => .75f,
						PhotoSize.Medium => .5f,
						PhotoSize.Small => .25f,
						PhotoSize.Custom => options.CustomPhotoSize / 100f,
					};

					if (options.PhotoSize == PhotoSize.MaxWidthHeight && options.MaxWidthHeight.HasValue)
					{
						var max = Math.Max(image.CGImage.Width, image.CGImage.Height);
						if (max > options.MaxWidthHeight.Value)
						{
							percent = (float)options.MaxWidthHeight.Value / (float)max;
						}
					}

					if (percent < 1.0f)
					{
						//begin resizing image
						image = image.ResizeImageWithAspectRatio(percent);
					}

				}
				catch (Exception ex)
				{
					Console.WriteLine($"Unable to compress image: {ex}");
				}
			}

			if (options.RotateImage)
			{
				image = image.RotateImage();
			}

			var (localId, meta) = GetImageMetadata(info);

			var quality = (options.CompressionQuality / 100f);  //iOS quality is 0.0-1.0
			var savedImage = false;
			if (meta != null)
			{
				savedImage = SaveImageWithMetadata(image, quality, meta, path);
			}

			if (!savedImage)
			{
				var imageData = GetImageWithQuality(quality, image);

				imageData.Save(path, true);
				imageData.Dispose();
			}

			var aPath = path;
			if (source != UIImagePickerControllerSourceType.Camera)
			{
				//try to get the album path's url
				var url = (NSUrl)info[UIImagePickerController.ReferenceUrl];
				aPath = url?.AbsoluteString;
			}
			else
			{
				if (options.SaveToAlbum)
				{
					PhotoLibraryAccess.SaveImageToGalery(path, options.Directory);
				}
			}

			var fullimage = image.CIImage;
			var media = new MediaFile(path, () => File.OpenRead(path), albumPath: aPath);
			SetMediaMetadata(localId, meta, ref media);
			return media;
		}