private void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs e)
        {
            UIImage image = e.EditedImage ?? e.OriginalImage;

            if (image != null)
            {
                NSData data;

                if (e.ReferenceUrl.PathExtension.ToUpper().Equals("PNG"))
                {
                    data = image.AsPNG();
                }
                else
                {
                    data = image.AsJPEG(1);
                }

                SharePhoto sharedPhoto = new SharePhoto
                {
                    ImageName = e.ReferenceUrl.ToString(),
                    ImageData = data.AsStream()
                };

                UnregisterEventHandlers();

                taskCompletionSource.SetResult(sharedPhoto);
            }
            else
            {
                UnregisterEventHandlers();
                taskCompletionSource.SetResult(null);
            }
            imagePicker.DismissModalViewController(true);
        }
Ejemplo n.º 2
0
 private static Stream GetStream(UIImage image)
 {
     using (image)
     {
         return(image.AsJPEG(0.8f).AsStream());
     }
 }
Ejemplo n.º 3
0
        void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs args)
        {
            UIImage image = args.EditedImage ?? args.OriginalImage;

            if (image != null)
            {
                // Convert UIImage to .NET Stream object
                NSData data   = image.AsJPEG(1);
                Stream stream = data.AsStream();

                UnregisterEventHandlers();

                // Set the Stream as the completion of the Task
                taskCompletionSource.SetResult(stream);



                //get path usage

                //var url = (NSUrl)args.Info.ValueForKey(new NSString("UIImagePickerControllerImageURL"));
                //taskCompletionSource.SetResult(url.Path);
            }
            else
            {
                //UnregisterEventHandlers();
                taskCompletionSource.SetResult(null);
            }
            imagePicker.DismissModalViewController(true);
        }
Ejemplo n.º 4
0
        public void AddNewQuest(UIImage image)
        {
            /*object[] alcoholKeys = { "Nombre", "Edad", "Correo", "Password", "Sexo", "rutaImagen" };
             * object[] alcoholValues = { "Andrea Hernandez De Alba", "21", "*****@*****.**", "123456789", "M", "qwerty" };
             * var qs2 = NSDictionary.FromObjectsAndKeys(alcoholValues, alcoholKeys, alcoholKeys.Length);
             * DatabaseReference rootNode = Database.DefaultInstance.GetRootReference();
             * DatabaseReference productosNode = rootNode.GetChild("0").GetChild("Usuarios");
             * DatabaseReference productoNode = productosNode.GetChildByAutoId();
             * productoNode.SetValue<NSDictionary>(qs2);*/
            var profileImageRef = rootRefStorage.GetChild($"/1/profile.jpg");

            var imageMetadata = new StorageMetadata
            {
                ContentType = "image/jpeg"
            };

            image = ResizeImage(image, 170, 170);

            profileImageRef.PutData(image.AsJPEG(), imageMetadata, (metadata, error) =>
            {
                if (error != null)
                {
                    Console.WriteLine("Error");
                }
            });
        }
Ejemplo n.º 5
0
        NSData SerializeImage (UIImage image, string typeIdentifier)
        {
            if (typeIdentifier == "public.png")
                return image.AsPNG ();

            return image.AsJPEG (JpegCompressionQuality);
        }
Ejemplo n.º 6
0
		private void HandleImagePick(UIImage image, int maxPixelDimension, int percentQuality, 
                                         Action<Stream> pictureAvailable, Action assumeCancelled)
		{
			if (image != null)
			{
				// resize the image
				image = image.ImageToFitSize (new SizeF (maxPixelDimension, maxPixelDimension));
				
				using (NSData data = image.AsJPEG ((float)((float)percentQuality/100.0)))
				{
					var byteArray = new byte [data.Length];
					Marshal.Copy (data.Bytes, byteArray, 0, Convert.ToInt32 (data.Length));
					
					var imageStream = new MemoryStream ();
					imageStream.Write (byteArray, 0, Convert.ToInt32 (data.Length));
					imageStream.Seek (0, SeekOrigin.Begin);
					
					pictureAvailable (imageStream);
				}
			}
			else
			{
				assumeCancelled ();
			}
			
			_picker.DismissModalViewControllerAnimated(true);
			_presenter.NativeModalViewControllerDisappearedOnItsOwn();
				
		}
Ejemplo n.º 7
0
 public static DumpValue AsImage(UIImage image)
 {
     var data = image.AsJPEG(0.6f);
     var dataBytes = new byte[data.Length];
     System.Runtime.InteropServices.Marshal.Copy(data.Bytes, dataBytes, 0, Convert.ToInt32(data.Length));
     return new DumpValue { TypeName = "___IMAGE___", DumpType = DumpValue.DumpTypes.Image, PrimitiveValue = Convert.ToBase64String(dataBytes) };
 }
Ejemplo n.º 8
0
        void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs args)
        {
            UIImage image = args.EditedImage ?? args.OriginalImage;

            if (image != null)
            {
                // Convert UIImage to .NET Stream object
                NSData data;
                if (args.ReferenceUrl.PathExtension.Equals("PNG") || args.ReferenceUrl.PathExtension.Equals("png"))
                {
                    data = image.AsPNG();
                }
                else
                {
                    data = image.AsJPEG(1);
                }
                Stream stream = data.AsStream();

                UnregisterEventHandlers();

                // Set the Stream as the completion of the Task
                taskCompletionSource.SetResult(stream);
            }
            else
            {
                UnregisterEventHandlers();
                taskCompletionSource.SetResult(null);
            }
            imagePicker.DismissModalViewController(true);
        }
        public override void DidCropToImage(TOCropViewController cropViewController, UIImage image, CoreGraphics.CGRect cropRect, nint angle)
        {
            IsCropped = true;

            try
            {
                if (image != null)
                {
                    _page.CroppedImage = image.AsJPEG().ToArray();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                if (image != null)
                {
                    image.Dispose();
                    image = null;
                }

                CloseView();
            }
        }
Ejemplo n.º 10
0
        void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs args)
        {
            UIImage image = args.EditedImage ?? args.OriginalImage;

            if (image != null)
            {
                // Convert UIImage to .NET Stream object
                NSData data = image.AsJPEG(1);
                imagePath = Path.Combine(documentsDirectory + "/imageSelected.jpg");
                NSError err = null;
                if (!data.Save(imagePath, false, out err))
                {
                    Console.WriteLine("Errore salvataggio foto temporanea, impossibile proseguire " + " Path " + imagePath);
                }
                Stream stream = data.AsStream();

                // Set the Stream as the completion of the Task
                taskCompletionSource.SetResult(stream);
            }
            else
            {
                taskCompletionSource.SetResult(null);
            }
            imagePicker.DismissModalViewController(true);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Plays custom objects found in frames of real time video.
        /// Each API call takes about 1-2s, therefore we have to introduce a
        /// busy lock in order not to overcrowd.
        /// This method cant be synchronous since it would block the changes
        /// in color of the background of the app.
        /// </summary>
        /// <param name="image">source image</param>
        /// <returns>Nothing</returns>
        public async Task PlayObjects(CGImage image)
        {
            if (busy)
            {
                return;
            }
            busy = true;
            CGSize size = new CGSize(image.Width, image.Height);

            UIGraphics.BeginImageContext(size);
            CGRect rect = new CGRect(CGPoint.Empty, size);

            UIImage.FromImage(image).Draw(rect);
            UIImage ui_image = UIGraphics.GetImageFromCurrentImageContext();

            UIGraphics.EndImageContext();
            using (Stream stream = ui_image.AsJPEG().AsStream())
            {
                var result = await endpoint.DetectImageAsync(project_id, published_name, stream);

                foreach (var prediction in result.Predictions)
                {
                    if (
                        supported_items_to_sounds.ContainsKey(prediction.TagName.ToLower()) &&
                        prediction.Probability > Constants.CONFIDENCE_TRESHOLD)
                    {
                        supported_items_to_sounds[prediction.TagName.ToLower()].Play();
                        break;
                    }
                }
            }
            busy = false;
        }
Ejemplo n.º 12
0
        public void ConvertImageToArray(UIImage image)
        {
            var data      = image.AsJPEG();
            var dataBytes = data.ToArray();

            ViewModel.ByteArray = dataBytes;
        }
Ejemplo n.º 13
0
        public void GetImageIntoCache(NSAction doWhenDone)
        {
            if (image == null)
            {
                if (CachedThumbExists(Program.ProgramId))
                {
                    image = UIImage.FromFileUncached(CachedThumbFullpath(Program.ProgramId));
                }
                else
                {
                    using (NSData imgData = NSData.FromUrl(new NSUrl(Program.ThumbnailUrl)))
                    {
                        using (UIImage tempimage = UIImage.LoadFromData(imgData))
                        {
                            image = ImageHelper.ResizeImage(tempimage, -1, 35);
                            NSData  data = image.AsJPEG();
                            NSError error;
                            data.Save(CachedThumbFullpath(Program.ProgramId), false, out error);
                        }
                    }
                }
            }

            doWhenDone();
        }
        public void SavePhoto(UIImage photo, string imageName, FileFormatEnum imageType)
        {
            var    documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string filePath           = System.IO.Path.Combine(documentsDirectory, imageName);
            NSData imgData;

            if (imageType == FileFormatEnum.PNG)
            {
                imgData = photo.AsPNG();
            }
            else
            {
                imgData = photo.AsJPEG();
            }

            NSError err = null;

            if (imgData.Save(filePath, false, out err))
            {
                Console.WriteLine("Saved image to " + filePath);
            }
            else
            {
                //Handle the Error!
                Console.WriteLine("Could NOT save to " + filePath + " because" + err.LocalizedDescription);
            }
        }
Ejemplo n.º 15
0
        async void TakePicture()
        {
            if (_resetCamera)
            {
                return;
            }

            var videoConnection = _stillImageOutput.ConnectionFromMediaType(AVMediaType.Video);
            var sampleBuffer    = await _stillImageOutput.CaptureStillImageTaskAsync(videoConnection);

            var jpegImage = AVCaptureStillImageOutput.JpegStillToNSData(sampleBuffer);

            var picture = new UIImage(jpegImage);

            SetPicture(true, picture);

            NSData  imgData            = picture.AsJPEG();
            NSError err                = null;
            var     documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            var     destinationPath    = System.IO.Path.Combine(documentsDirectory, "picture.jpg");

            if (imgData.Save(destinationPath, false, out err))
            {
                Console.WriteLine("saved as " + destinationPath);
                Callback(destinationPath);
            }
            else
            {
                Console.WriteLine("NOT saved as " + destinationPath + " because" + err.LocalizedDescription);
            }
        }
		public async Task<string> SaveImageToTemporaryFileJpeg(UIImage image, float quality = 1.0f)
		{
			var uniqueFileNamePortion = Guid.NewGuid().ToString();
			var temporaryImageFileName = string.Format("{0}.jpg", uniqueFileNamePortion);

			var documentsFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
			var temporaryStorageFolderPath = Path.Combine(documentsFolderPath, "..", "tmp");

			var temporaryImageFilePath = Path.Combine(temporaryStorageFolderPath, temporaryImageFileName);

			var imageData = image.AsJPEG(quality);
			await Task.Run(() => 
			{
				//File.WriteAllBytes(temporaryImageFilePath, imageData);
				NSError error = null;
				if (imageData.Save(temporaryImageFilePath, false, out error)) 
				{
					Console.WriteLine("Saved image to temporary file: " + temporaryImageFilePath);
				} else 
				{
					Console.WriteLine("ERROR! Did NOT SAVE file because" + error.LocalizedDescription);
				}
			});

			return temporaryImageFilePath;
		}
        private async Task <OperationResult <MediaModel> > UploadPhoto(UIImage photo, NSDictionary metadata)
        {
            Stream stream = null;

            try
            {
                var compression    = 1f;
                var maxCompression = 0.1f;
                int maxFileSize    = _photoSize * 1024;

                var byteArray = photo.AsJPEG(compression);

                while (byteArray.Count() > maxFileSize && compression > maxCompression)
                {
                    compression -= 0.1f;
                    byteArray    = photo.AsJPEG(compression);
                }

                if (metadata != null)
                {
                    //exif setup
                    var editedExifData       = RemakeMetadata(metadata, photo);
                    var newImageDataWithExif = new NSMutableData();
                    var imageDestination     = CGImageDestination.Create(newImageDataWithExif, "public.jpeg", 0);
                    imageDestination.AddImage(new UIImage(byteArray).CGImage, editedExifData);
                    imageDestination.Close();
                    stream = newImageDataWithExif.AsStream();
                }
                else
                {
                    stream = byteArray.AsStream();
                }

                var request = new UploadMediaModel(AppSettings.User.UserInfo, stream, ImageExtension);
                return(await _presenter.TryUploadMedia(request));
            }
            catch (Exception ex)
            {
                AppSettings.Reporter.SendCrash(ex);
                return(new OperationResult <MediaModel>(new AppError(LocalizationKeys.PhotoProcessingError)));
            }
            finally
            {
                stream?.Flush();
                stream?.Dispose();
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Converts the png image to jpg image.
        /// </summary>
        /// <returns>The jpg image.</returns>
        /// <param name="image">The original image.</param>
        public async Task <byte[]> ConvertPngToJpgAsync(byte[] image, int quality)
        {
            UIImage uiImage = await image.ToImageAsync();

            nfloat fQuality = quality / 100;

            return(uiImage.AsJPEG(fQuality).ToArray());
        }
Ejemplo n.º 19
0
        protected async void Handle_FinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs e)
        {
            try
            {
                //Console.WriteLine("Enterd into Gallery pick");
                // determine what was selected, video or image
                bool isImage = false;
                switch (e.Info[UIImagePickerController.MediaType].ToString())
                {
                case "public.image":
                    //Console.WriteLine("Image selected");
                    isImage = true;
                    break;

                case "public.video":
                    //Console.WriteLine("Video selected");
                    break;
                }
                if (isImage)
                {
                    // get the original image

                    UIImage originalImage = e.Info[UIImagePickerController.OriginalImage] as UIImage;
                    if (originalImage != null)
                    {
                        // do something with the image

                        //Console.WriteLine("got the original image");
                        imgprofilepic.Image = originalImage;                         // display
                        using (NSData imagedata = originalImage.AsJPEG())
                        {
                            byte[] myByteArray = new byte[imagedata.Length];
                            System.Runtime.InteropServices.Marshal.Copy(imagedata.Bytes,
                                                                        myByteArray, 0, Convert.ToInt32(imagedata.Length));

                            byte[] img = BlobWrapper.ResizeImageIOS(myByteArray, 250, 300);
                            int    i   = img.Length;
                            await BlobWrapper.UploadProfilePic(img, i);
                        }
                    }
                }
                else
                {                 // if it's a video
                                  // get video url
                    NSUrl mediaURL = e.Info[UIImagePickerController.MediaURL] as NSUrl;
                    if (mediaURL != null)
                    {
                        //Console.WriteLine(mediaURL.ToString());
                    }
                }
                // dismiss the picker
                imagePicker.DismissModalViewController(true);
            }
            catch (Exception ex)
            {
                LoggingClass.LogError(ex.ToString(), screenid, ex.StackTrace);
            }
        }
Ejemplo n.º 20
0
 public static void ImageToByteArray(UIImage image, out byte[] mediaByteArray)
 {
     using (NSData imgData = image.AsJPEG())
     {
         mediaByteArray = new byte[imgData.Length];
         System.Runtime.InteropServices.Marshal.Copy(imgData.Bytes, mediaByteArray, 0, Convert.ToInt32(imgData.Length));
     }
     image.Dispose();
 }
Ejemplo n.º 21
0
        public async Task <Byte[]> CapturePhotoCropped(CropRatios cropRatios)
        {
            var videoConnection = StillImageOutput.ConnectionFromMediaType(AVMediaType.Video);
            var sampleBuffer    = await StillImageOutput.CaptureStillImageTaskAsync(videoConnection);

            var jpegImageAsNsData = AVCaptureStillImageOutput.JpegStillToNSData(sampleBuffer);

            UIImage imageInfo = new UIImage(jpegImageAsNsData);

            // The following code would rotate the image based on the device orientation, but currently we lock to landscape.
            //****************************************

            //UIImageOrientation? orientationToApply = null;

            //switch (GetVideoOrientationFromDevice())
            //{
            //    case AVCaptureVideoOrientation.Portrait:
            //        orientationToApply = UIImageOrientation.Right;
            //        break;
            //    case AVCaptureVideoOrientation.LandscapeLeft:
            //        orientationToApply = UIImageOrientation.Down;
            //        break;
            //    case AVCaptureVideoOrientation.LandscapeRight:
            //        orientationToApply = null;
            //        break;
            //    case AVCaptureVideoOrientation.PortraitUpsideDown:
            //        orientationToApply = UIImageOrientation.Left;
            //        break;
            //    default:
            //        break;
            //}

            //var rotatedImage = ScaleAndRotateImage(imageInfo, orientationToApply);

            //****************************************

            nfloat cropPhotoX = (nfloat)(cropRatios.LeftRatio * imageInfo.Size.Width);
            nfloat cropPhotoY = (nfloat)(cropRatios.TopRatio * imageInfo.Size.Height);

            nfloat cropPhotoWidth  = (nfloat)(imageInfo.Size.Width * (1 - (cropRatios.LeftRatio + cropRatios.RightRatio)));
            nfloat cropPhotoHeight = (nfloat)(imageInfo.Size.Height * (1 - (cropRatios.TopRatio + cropRatios.BottomRatio)));

            var croppedImage = CropImage(imageInfo, cropPhotoX, cropPhotoY, cropPhotoWidth, cropPhotoHeight);

            // Rotate after cropping since we are locking orentation to landscape. Otherwise this line should be removed.
            var rotatedImage = ScaleAndRotateImage(croppedImage, UIImageOrientation.Left);

            Byte[] imageByteArray;

            using (Foundation.NSData imageData = imageInfo.AsJPEG())
            {
                imageByteArray = new Byte[imageData.Length];
                System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, imageByteArray, 0, Convert.ToInt32(imageData.Length));
            }

            return(imageByteArray);
        }
Ejemplo n.º 22
0
        public static byte[] ToBytes(this UIImage image)
        {
            var imageData  = image.AsJPEG(0.7f);
            var imageBytes = new byte[imageData.Length];

            Marshal.Copy(imageData.Bytes, imageBytes, 0, Convert.ToInt32(imageData.Length));

            return(imageBytes);
        }
Ejemplo n.º 23
0
        private static void SaveTempImage(CIImage fullimage, UIImage image, string outputFilename, int quality, bool rotate)
        {
            var imageData       = image.AsJPEG(quality);
            var dataProvider    = new CGDataProvider(imageData);
            var cgImageFromJpeg = CGImage.FromJPEG(dataProvider, null, false, CGColorRenderingIntent.Default);
            var imageWithExif   = new NSMutableData();
            var destination     = CGImageDestination.Create(imageWithExif, UTType.JPEG, 1);
            var cgImageMetadata = new CGMutableImageMetadata();
            var options         = new CGImageDestinationOptions();

            if (fullimage.Properties.DPIWidthF != null)
            {
                options.Dictionary[ImageIO.CGImageProperties.DPIWidth] =
                    new NSNumber((nfloat)fullimage.Properties.DPIWidthF);
            }
            if (fullimage.Properties.DPIWidthF != null)
            {
                options.Dictionary[ImageIO.CGImageProperties.DPIHeight] =
                    new NSNumber((nfloat)fullimage.Properties.DPIHeightF);
            }
            options.ExifDictionary = fullimage.Properties?.Exif ?? new CGImagePropertiesExif();
            options.TiffDictionary = fullimage.Properties?.Tiff ?? new CGImagePropertiesTiff();
            options.GpsDictionary  = fullimage.Properties?.Gps ?? new CGImagePropertiesGps();
            options.JfifDictionary = fullimage.Properties?.Jfif ?? new CGImagePropertiesJfif();
            options.IptcDictionary = fullimage.Properties?.Iptc ?? new CGImagePropertiesIptc();
            if (rotate)
            {
                options.Dictionary[ImageIO.CGImageProperties.Orientation] =
                    new NSString(UIImageOrientation.Up.ToString());
                var tiffDict = new CGImagePropertiesTiff();
                foreach (KeyValuePair <NSObject, NSObject> x in options.TiffDictionary.Dictionary)
                {
                    tiffDict.Dictionary.SetValueForKey(x.Value, x.Key as NSString);
                }
                tiffDict.Dictionary.SetValueForKey(new NSNumber(1), new NSString("Orientation"));
                options.TiffDictionary = tiffDict;
            }
            else
            {
                if (fullimage.Properties.Orientation != null)
                {
                    options.Dictionary[ImageIO.CGImageProperties.Orientation] =
                        new NSString(image.Orientation.ToString());
                }
            }
            destination.AddImageAndMetadata(cgImageFromJpeg, cgImageMetadata, options);
            var success = destination.Close();

            if (success)
            {
                imageWithExif.Save(outputFilename, true);
            }
            else
            {
                imageData.Save(outputFilename, true);
            }
        }
Ejemplo n.º 24
0
        private void SaveImage(string targetFile, UIImage resultImage)
        {
            if (!Directory.Exists(Path.GetDirectoryName(targetFile)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
            }

            resultImage.AsJPEG(0.75f).Save(targetFile, true);
        }
//        public override void TouchesBegan(NSSet touches, UIEvent evt) {
//            base.TouchesBegan(touches, evt);
//            if (this.onResult == null)
//                this.DismissViewController(true, null);
//        }


        private static Stream GetImageStream(UIImage image, ImageFormatType formatType)
        {
            if (formatType == ImageFormatType.Jpg)
            {
                return(image.AsJPEG().AsStream());
            }

            return(image.AsPNG().AsStream());
        }
Ejemplo n.º 26
0
        public byte[] ResizeTheImage(byte[] imageData, float width, float height)
        {
            UIImage originalImage = ImageFromByteArray(imageData);

            originalImage = MaxResizeImage(originalImage, width, height);
            UIImageOrientation orientation = originalImage.Orientation;

            return(originalImage.AsJPEG().ToArray());
        }
Ejemplo n.º 27
0
        public static string ToBase64String(this UIImage image)
        {
            var imageData  = image.AsJPEG(0.3f);
            var imageBytes = new byte[imageData.Length];

            Marshal.Copy(imageData.Bytes, imageBytes, 0, Convert.ToInt32(imageData.Length));

            return(Convert.ToBase64String(imageBytes));
        }
Ejemplo n.º 28
0
        static NSData GetImageData(UIImage image)
        {
            if (Extension.Equals(PNG))
            {
                return(image.AsPNG());
            }

            return(image.AsJPEG());
        }
Ejemplo n.º 29
0
 public static void ImageToByteArray(UIImage image, out byte[] mediaByteArray)
 {
     using (NSData imgData = image.AsJPEG ())
     {
         mediaByteArray = new byte[imgData.Length];
         System.Runtime.InteropServices.Marshal.Copy (imgData.Bytes, mediaByteArray, 0, Convert.ToInt32 (imgData.Length));
     }
     image.Dispose ();
 }
Ejemplo n.º 30
0
        private string getSignatureString(UIImage signatureImage)
        {
            NSData signatureData = signatureImage.AsJPEG();

            Byte[] signatureByteArray = new byte[signatureData.Length];
            System.Runtime.InteropServices.Marshal.Copy (signatureData.Bytes, signatureByteArray, 0, Convert.ToInt32 (signatureData.Length));

            return System.Convert.ToBase64String(signatureByteArray);
        }
Ejemplo n.º 31
0
        private async void SelectImageFromCamera()
        {
            #region FromCamera
            Camera.TakePicture(this, (obj) =>
            {
                PhotoCapture = new UIImage();
                PhotoCapture = obj.ValueForKey(new NSString("UIImagePickerControllerOriginalImage")) as UIImage;
                // ivUserProfilePic.Image = PhotoCapture;

                // This bit of code saves to the application's Documents directory, doesn't save metadata

                documentsDirectory = Environment.GetFolderPath
                                         (Environment.SpecialFolder.Personal);
                string imagename = "myAttachmentTemp" + DateTime.UtcNow.ToString("ddMMyyyyhhmmss") + ".jpg";
                filePath         = System.IO.Path.Combine(documentsDirectory, imagename);
                NSData imgData   = PhotoCapture.AsJPEG();
                NSError err      = null;

                if (imgData.Save(filePath, false, out err))
                {
                    Console.WriteLine("saved as " + filePath);
                }
                else
                {
                    Console.WriteLine("NOT saved as" + filePath + " because" + err.LocalizedDescription);
                }

                UIImage ThumbImage  = ImageClass.MaxResizeImage(PhotoCapture, 100, 100);
                var originalpath    = NSUrl.FromFilename(filePath).RelativePath;
                thumbFilePath       = originalpath.Replace(Path.GetExtension(originalpath), "-thumb" + Path.GetExtension(originalpath));
                NSData thumbimgData = PhotoCapture.AsJPEG();
                if (thumbimgData.Save(thumbFilePath, false, out err))
                {
                    Console.WriteLine("saved as " + thumbFilePath);
                }
                else
                {
                    Console.WriteLine("NOT saved as" + thumbFilePath + " because" + err.LocalizedDescription);
                }

                SendMedia(filePath, "Photo");
            });
            #endregion
        }
Ejemplo n.º 32
0
        private string SavePhotosToSharedStorage(UIImage photo, int imageIndex)
        {
            var nsFileManager = new NSFileManager();
            var containerUrl  = nsFileManager.GetContainerUrl(APP_SHARE_GROUP);
            var fileName      = string.Format("image{0}.jpg", imageIndex);
            var filePath      = Path.Combine(containerUrl.Path, fileName);

            photo.AsJPEG(1).Save(filePath, true);
            return(filePath);
        }
Ejemplo n.º 33
0
        public static bool SaveRotateImage(String imagePath)
        {
            UIImage imageCopy = GetRotateImage(imagePath);

            NSData  data     = imageCopy.AsJPEG();
            NSError error    = new NSError();
            bool    bSuccess = data.Save(imagePath, true, out error);

            return(bSuccess);
        }
        // Save the uploaded image to disk.
        void SaveImageToDisk(string imageId, UIImage image)
        {
            string imageFullPath = Path.Combine(GetTempFolderToNote(), imageId);

            NSData imageData = image.AsJPEG();

            NSError error;

            imageData.Save(imageFullPath, false, out error);
        }
Ejemplo n.º 35
0
        public Stream ResizeImage(Stream stream)
        {
            // Load the bitmap
            UIImage originalImage = ImageFromByteArray(ReadFully(stream));
            //
            var    bytesImagen    = originalImage.AsJPEG(0.5f).ToArray();
            Stream compressStream = new MemoryStream(bytesImagen);

            return(compressStream);
        }
Ejemplo n.º 36
0
        public static DumpValue AsImage(UIImage image)
        {
            var data      = image.AsJPEG(0.6f);
            var dataBytes = new byte[data.Length];

            System.Runtime.InteropServices.Marshal.Copy(data.Bytes, dataBytes, 0, Convert.ToInt32(data.Length));
            return(new DumpValue {
                TypeName = "___IMAGE___", DumpType = DumpValue.DumpTypes.Image, PrimitiveValue = Convert.ToBase64String(dataBytes)
            });
        }
        public static byte[] ExportToJpg(UIImage image)
        {
            using (NSData data = image.AsJPEG(1)) {
                byte[] binaryData = new byte[data.Length];

                // Copy the unmanaged data hold by the NSData to a new managed byte array.
                System.Runtime.InteropServices.Marshal.Copy(data.Bytes, binaryData, 0, (int)data.Length);

                return binaryData;
            }
        }
        public override void FinishedPickingImage(UIImagePickerController picker, UIImage image, NSDictionary editingInfo)
        {
            // Here you can do anything with the image... save for example.
            var documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string jpgFilename = System.IO.Path.Combine(documentsDirectory, string.Format("{0}.jpg", Guid.NewGuid()));

            using (NSData imageData = image.AsJPEG(0.2f))
            {
                NSError err;
                if (!imageData.Save(jpgFilename, false, out err))
                {
                    Console.WriteLine("Saving of file failed: " + err.Description);
                }
            }
        }
Ejemplo n.º 39
0
		public ImageData (UIImage image, string filename)
		{
			if (image == null) {
				throw new ArgumentNullException ("image");
			}
			if (string.IsNullOrEmpty (filename)) {
				throw new ArgumentException ("filename");
			}

			Image = image;
			Filename = filename;

			MimeType = (filename.ToLowerInvariant ().EndsWith (".png")) ?
				"image/png" : "image/jpeg";

			if (MimeType == "image/png") {
				Data = new NSDataStream (image.AsPNG ());
			}
			else {
				Data = new NSDataStream (image.AsJPEG ());
			}
		}
Ejemplo n.º 40
0
        /// <summary>
        /// Sends the specified UIImage to the AirPlay device.
        /// </summary>
        /// <param name='service'>
        /// NSNetService (extension method target) representing the AirPlay device.
        /// </param>
        /// <param name='image'>
        /// The UIImage to be send to the device.
        /// </param>
        /// <param name='complete'>
        /// Optional method to be called when the operation is complete. True will be supplied if the action was
        /// successful, false if a problem occured.
        /// </param>
        public static unsafe void SendTo(this NSNetService service, UIImage image, Action<bool> complete)
        {
            if (service == null) {
                if (complete != null)
                    complete (false);
                return;
            }

            // In general I prefer WebClient *Async methods but it does not provide methods to
            // upload Stream and allocating a (not really required) byte[] is a huge waste
            ThreadPool.QueueUserWorkItem (delegate {
                bool ok = true;
                try {
                    string url = String.Format ("http://{0}:{1}/photo", service.HostName, service.Port);
                    HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
                    using (var data = image.AsJPEG ()) {
                        req.Method = "PUT";
                        req.ContentLength = data.Length;
                        req.UserAgent = "AirPlay/160.4 (Photos)";
                        req.Headers.Add ("X-Apple-AssetKey", Guid.NewGuid ().ToString ());
                        req.Headers.Add ("X-Apple-Session-ID", session.ToString ());
                        var s = req.GetRequestStream ();
                        using (Stream ums = new UnmanagedMemoryStream ((byte *) data.Bytes, data.Length))
                            ums.CopyTo (s);
                    }
                    req.GetResponse ().Dispose ();
                }
                catch {
                    ok = false;
                }
                finally {
                    if (complete != null) {
                        NSRunLoop.Main.InvokeOnMainThread (delegate {
                            complete (ok);
                        });
                    }
                }
            });
        }
        public MediaFile GetPictureMediaFile(UIImage image)
        {
            string path = GetOutputPath (MediaPicker.TypeImage, "temp", options.Name);

            using (FileStream fs = File.OpenWrite (path))
            using (Stream s = new NSDataStream (image.AsJPEG ())) {
                s.CopyTo (fs);
                fs.Flush ();
            }

            Action<bool> dispose = null;
            dispose = d => File.Delete (path);

            return new MediaFile (path, () => File.OpenRead (path), dispose);
        }
Ejemplo n.º 42
0
        public static bool Save(string tailNumber, UIImage photo, bool thumbnail, out NSError error)
        {
            string path = Path.Combine (PhotosDir, string.Format ("{0}{1}.jpg", tailNumber, thumbnail ? "-thumb" : ""));

            if (thumbnail)
                ThumbnailCache[tailNumber] = photo;

            if (!photo.AsJPEG ().Save (path, true, out error))
                return false;

            return true;
        }
		//-------------------------------------------------------------------------
		private byte[] UIImageViewToByteArray(UIImage uiimg)
		{
			Byte[] bytes = null;
			using (NSData imageData = uiimg.AsJPEG())
			{
				bytes = new byte[imageData.Length];
				System.Runtime.InteropServices.Marshal.Copy
					(imageData.Bytes, bytes, 0, Convert.ToInt32(imageData.Length));
			}

			return bytes;
		}
		public void SaveImage(UIImage image)
		{
			_imagePicked = true;

			string filepath = Path.Combine(Environment.GetFolderPath (Environment.SpecialFolder.Personal), _filename);
			   
			using (NSData imageData = image.AsJPEG())
			{
				NSError err = new NSError();
				imageData.Save(filepath, true, out err);
			}
			imageView.Image = image;
			
			loadView.StopAnimating();
			InitBarButtons();
			_callback(this);
			
			this.DismissModalViewControllerAnimated(true);
		}
Ejemplo n.º 45
0
        void save()
        {
            using (new NSAutoreleasePool())
            {
                NSError error = new NSError();
                selectedImage = Graphics.PrepareForUpload(selectedImage);
                selectedImage.AsJPEG().Save(Path.Combine(Util.PicDir,Value),NSDataWritingOptions.Atomic,out error);
                NSObject invoker = new NSObject();
                invoker.InvokeOnMainThread(delegate {
                    completed();
                });

            }
        }
Ejemplo n.º 46
0
        public void GetImageIntoCache(NSAction doWhenDone)
        {
            if (image == null)
            {
                if (CachedThumbExists(Program.ProgramId))
                {

                    image = UIImage.FromFileUncached(CachedThumbFullpath(Program.ProgramId));
                } else
                {

                    using (NSData imgData = NSData.FromUrl(new NSUrl(Program.ThumbnailUrl)))
                    {
                        using (UIImage tempimage = UIImage.LoadFromData(imgData))
                        {
                            image = ImageHelper.ResizeImage(tempimage, -1, 35);
                            NSData data = image.AsJPEG();
                            NSError error;
                            data.Save(CachedThumbFullpath(Program.ProgramId), false, out error);

                        }
                    }
                }
            }

            doWhenDone();
        }
//        public override void TouchesBegan(NSSet touches, UIEvent evt) {
//            base.TouchesBegan(touches, evt);
//            if (this.onResult == null)
//                this.DismissViewController(true, null);
//        }


        private static Stream GetImageStream(UIImage image, ImageFormatType formatType) {
            if (formatType == ImageFormatType.Jpg)
                return image.AsJPEG().AsStream();

            return image.AsPNG().AsStream();
        }
Ejemplo n.º 48
0
        private ImageUploadResult SendImage(UIImage image)
        {
            var address = "BunkNotes/InsertBNoteImage?CampId={CampId}&Token={Token}";
            var request = new RestRequest (address, Method.POST);
            request.AddUrlSegment("CampId",RestManager.AuthenticationResult.CampId.ToString());
            request.AddUrlSegment("Token",RestManager.AuthenticationResult.Token);

            ActivityIndicatorAlertView activityIndicator;
            var thread = new Thread (() => activityIndicator = ActivityIndicatorAlertView.Show ("sending the image"));
            thread.Start ();
            ImageUploadResult result = null;

            using (NSData imageData = image.AsJPEG()) {
                Byte[] imgByteArray = new Byte[imageData.Length];
                System.Runtime.InteropServices.Marshal.Copy (imageData.Bytes, imgByteArray, 0, Convert.ToInt32 (imageData.Length));
                request.AddFile ("DataString", imgByteArray, "filename");
            }

            var task = Task<RestResponse>.Factory.StartNew (() => {
                return _client.Execute (request);
            });
            task.ContinueWith (t => {
                activityIndicator.Hide (animated:true);
            }, TaskScheduler.FromCurrentSynchronizationContext ());
            task.Wait();
            result = JsonParser.ImageUploadResult (task.Result.Content);
            return result;
        }
    private async void SendImage(UIImage image)
    {
      try
      {
        using (ISitecoreWebApiSession session = this.instanceSettings.GetSession())
        {
          Stream stream = image.AsJPEG().AsStream();

          var request = ItemWebApiRequestBuilder.UploadResourceRequestWithParentPath(itemPathTextField.Text)
            .ItemDataStream(stream)
            .ContentType("image/jpg")
            .ItemName(this.itemNameTextField.Text)
            .FileName("imageFile.jpg")
            .Build();

          this.ShowLoader();

          var response = await session.UploadMediaResourceAsync(request);

          if (response != null)
          {
            AlertHelper.ShowAlertWithOkOption("upload image result","The image uploaded successfuly");
          }
          else
          {
            AlertHelper.ShowAlertWithOkOption("upload image result","something wrong");
          }
        }
      }
      catch(Exception e) 
      {
        AlertHelper.ShowLocalizedAlertWithOkOption("Error", e.Message);
      }
      finally
      {
        BeginInvokeOnMainThread(delegate
        {
          this.HideLoader();
        });
      }
    }
Ejemplo n.º 50
0
        public MediaFile GetPictureMediaFile(NSDictionary info=null, UIImage image=null)
        {
            if (image == null) {
                image = (UIImage)info [UIImagePickerController.EditedImage];
                if (image == null)
                    image = (UIImage)info [UIImagePickerController.OriginalImage];
            }
            string path = GetOutputPath (MediaPicker.TypeImage,
                options.Directory ?? ((IsCaptured) ? String.Empty : "temp"),
                options.Name);

            using (FileStream fs = File.OpenWrite (path))
            using (Stream s = new NSDataStream (image.AsJPEG()))
            {
                s.CopyTo (fs);
                fs.Flush();
            }

            Action<bool> dispose = null;
            if (this.source != UIImagePickerControllerSourceType.Camera)
                dispose = d => File.Delete (path);

            return new MediaFile (path, () => File.OpenRead (path), dispose);
        }
        private void HandleImagePick(UIImage image)
        {
            ClearCurrentlyActive();
            if (image != null)
            {
                if (_maxPixelDimension > 0 &&(image.Size.Height > _maxPixelDimension || image.Size.Width > _maxPixelDimension))
				{
					// resize the image
					image = image.ImageToFitSize(new SizeF(_maxPixelDimension, _maxPixelDimension));
				}

                using (NSData data = image.AsJPEG((float)(_percentQuality / 100.0)))
                {
                    var byteArray = new byte[data.Length];
                    Marshal.Copy(data.Bytes, byteArray, 0, Convert.ToInt32(data.Length));

                    var imageStream = new MemoryStream(byteArray, false);
                    if (_pictureAvailable != null)
                        _pictureAvailable(imageStream);
                }
            }
            else
            {
                if (_assumeCancelled != null)
                    _assumeCancelled();
            }

            _picker.DismissViewController(true, () => { });
            _modalHost.NativeModalViewControllerDisappearedOnItsOwn();
        }
        private async void UploadImage(UIImage img)
        {
            var hud = new CodeFramework.iOS.Utils.Hud(null);
            hud.Show("Uploading...");

            try
            {
                var returnData = await Task.Run<byte[]>(() => 
                {
                    using (var w = new WebClient())
                    {
                        var data = img.AsJPEG();
                        byte[] dataBytes = new byte[data.Length];
                        System.Runtime.InteropServices.Marshal.Copy(data.Bytes, dataBytes, 0, Convert.ToInt32(data.Length));

                        w.Headers.Set("Authorization", "Client-ID aa5d7d0bc1dffa6");

                        var values = new NameValueCollection
                        {
                            { "image", Convert.ToBase64String(dataBytes) }
                        };

                        return w.UploadValues("https://api.imgur.com/3/image", values);
                    }
                });


                var json = Mvx.Resolve<IJsonSerializationService>();
                var imgurModel = json.Deserialize<ImgurModel>(System.Text.Encoding.UTF8.GetString(returnData));
                TextView.InsertText("![](" + imgurModel.Data.Link + ")");
            }
            catch (Exception e)
            {
                MonoTouch.Utilities.ShowAlert("Error", "Unable to upload image: " + e.Message);
            }
            finally
            {
                hud.Hide();
            }
        }
Ejemplo n.º 53
0
        public void Save(string path, ImageFormat format)
        {
            if (path == null)
                throw new ArgumentNullException ("path");

            if (NativeCGImage == null)
                throw new ObjectDisposedException ("cgimage");

            using (var uiimage = new UIImage (NativeCGImage)){
                NSError error;

                if (format == ImageFormat.Jpeg){
                    using (var data = uiimage.AsJPEG ()){
                        if (data.Save (path, NSDataWritingOptions.Atomic, out error))
                            return;

                        throw new IOException ("Saving the file " + path + " " + error);
                    }
                } else if (format == ImageFormat.Png){
                    using (var data = uiimage.AsPNG ()){
                        if (data.Save (path, NSDataWritingOptions.Atomic, out error))
                            return;

                        throw new IOException ("Saving the file " + path + " " + error);
                    }
                } else
                    throw new ArgumentException ("Unsupported format, only Jpeg and Png are supported", "format");
            }
        }