NSData SerializeImage (UIImage image, string typeIdentifier)
        {
            if (typeIdentifier == "public.png")
                return image.AsPNG ();

            return image.AsJPEG (JpegCompressionQuality);
        }
Example #2
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) };
 }
		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();
				
		}
		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;
		}
Example #5
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 ();
 }
        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);
        }
        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);
                }
            }
        }
Example #9
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 ());
			}
		}
Example #10
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);
                        });
                    }
                }
            });
        }
Example #11
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();
        }
		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);
		}
        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();
                });

            }
        }
    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();
        });
      }
    }
        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();
            }
        }
Example #18
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");
            }
        }
        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);
        }
Example #20
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;
        }
Example #21
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;
        }
        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);
        }
		//-------------------------------------------------------------------------
		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;
		}