private static NSData GetData(UIImage image, ImageType type, int quality)
 {
     var floatQuality = quality/100f;
     switch(type)
     {
         case ImageType.Jpg:
             return image.AsJPEG(floatQuality);
         case ImageType.Png:
             return image.AsPNG();
         default:
             return image.AsJPEG(floatQuality);
     }
 } 
예제 #2
0
        public async System.Threading.Tasks.Task <byte[]> ResizeImage(byte[] imageStream, float width, float height)
        {
            //Create image using byte array...
            UIImage originalImage = ImageFromByteArray(imageStream);

            //Send image for roation... if its not up...
            byte[] rotatedimg = RotateImage(originalImage);

            //Create a new image with the byte array returned from RotateImage()...

            UIImage newimage = ImageFromByteArray(rotatedimg);

            //create a 24bit RGB image
            using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero,
                                                                 (int)width, (int)height, 8,
                                                                 (int)(4 * width), CGColorSpace.CreateDeviceRGB(),
                                                                 CGImageAlphaInfo.PremultipliedFirst))
            {
                CGRect imageRect = new CGRect(0, 0, width, height);

                // draw the image
                context.DrawImage(imageRect, newimage.CGImage);

                //UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 0, orientation);
                UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage());

                // save the image as a jpeg
                return(resizedImage.AsJPEG().ToArray());
            }
        }
예제 #3
0
        public static FileStream ResizeImageIOS(Stream imageData, float width, float height)
        {
            UIImage            originalImage = ImageFromByteArray(imageData);
            UIImageOrientation orientation   = originalImage.Orientation;

            //create a 24bit RGB image
            using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero,
                                                                 (int)width, (int)height, 8,
                                                                 4 * (int)width, CGColorSpace.CreateDeviceRGB(),
                                                                 CGImageAlphaInfo.PremultipliedFirst))
            {
                RectangleF imageRect = new RectangleF(0, 0, width, height);

                // draw the image
                context.DrawImage(imageRect, originalImage.CGImage);

                UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 0, orientation);
                string        path         = Path.Combine(Kit.Tools.Instance.TemporalPath, $"{Guid.NewGuid():N}.jpeg");
                using (FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    using (MemoryStream memoryStream = new MemoryStream(resizedImage.AsJPEG().ToArray()))
                    {
                        memoryStream.Position = 0;
                        memoryStream.CopyTo(fileStream);
                        return(fileStream);
                    }
                }
                // save the image as a jpeg
            }
        }
        /// <summary>
        /// Save UIImage into directory
        /// </summary>
        /// <param name="image"></param>
        void Save(UIKit.UIImage image)
        {
            var documentsDirectory = Environment.GetFolderPath
                                         (Environment.SpecialFolder.Personal);
            var directoryname = Path.Combine(documentsDirectory, "FolderName");

            Directory.CreateDirectory(directoryname);

            string jpgFile = System.IO.Path.Combine(directoryname, "image.jpg");

            Foundation.NSData  imgData = image.AsJPEG();
            Foundation.NSError err     = null;
            if (imgData.Save(jpgFile, false, out err))
            {
                Console.WriteLine("saved as" + jpgFile);
            }
            else
            {
                Console.WriteLine("not saved as " + jpgFile + "because" + err.LocalizedDescription);
            }
            var alert = UIAlertController.Create("Saved Location", jpgFile, UIAlertControllerStyle.Alert);

            alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
            ShowViewController(alert, null);
        }
예제 #5
0
        public byte[] ResizeImage(byte[] imageData)
        {
            UIImage            originalImage = ImageFromByteArray(imageData);
            UIImageOrientation orientation   = originalImage.Orientation;

            int width  = (int)originalImage.Size.Width;
            int height = (int)originalImage.Size.Height;

            //create a 24bit RGB image
            using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero,
                                                                 (int)width, (int)height, 8,
                                                                 (int)(4 * width), CGColorSpace.CreateDeviceRGB(),
                                                                 CGImageAlphaInfo.PremultipliedFirst))
            {
                RectangleF imageRect = new RectangleF(0, 0, width, height);

                // draw the image
                context.DrawImage(imageRect, originalImage.CGImage);

                UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 0, orientation);

                // save the image as a jpeg
                return(resizedImage.AsJPEG().ToArray());
            }
        }
예제 #6
0
        public async Task <bool> SaveImage(string directory, string filename, ImageSource img)
        {
            bool success = false;

            NSData imgData  = null;
            var    renderer = new Xamarin.Forms.Platform.iOS.StreamImagesourceHandler();

            UIKit.UIImage photo = await renderer.LoadImageAsync(img);

            var savedImageFilename = System.IO.Path.Combine(directory, filename);

            NSFileManager.DefaultManager.CreateDirectory(directory, true, null);

            if (System.IO.Path.GetExtension(filename).ToLower() == ".png")
            {
                imgData = photo.AsPNG();
            }
            else
            {
                imgData = photo.AsJPEG(100);
            }

            NSError err = null;

            success = imgData.Save(savedImageFilename, NSDataWritingOptions.Atomic, out err);

            return(success);
        }
예제 #7
0
        public Stream GetJPGStreamFromByteArray(byte[] image)
        {
            // test
            UIKit.UIImage images    = new UIKit.UIImage(Foundation.NSData.FromArray(image));
            byte[]        bytes     = images.AsJPEG(100).ToArray();
            Stream        imgStream = new MemoryStream(bytes);

            return(imgStream);
        }
        public byte[] ResizeImage(byte[] imageData, float width, float height)
        {
            UIImage            originalImage = ImageFromByteArray(imageData);
            UIImageOrientation orientImg     = originalImage.Orientation;

            float oldWidth    = (float)originalImage.Size.Width;
            float oldHeight   = (float)originalImage.Size.Height;
            float scaleFactor = 0f;

            if (oldWidth > oldHeight)
            {
                scaleFactor = width / oldWidth;
            }
            else
            {
                scaleFactor = height / oldHeight;
            }

            float newHeight = oldHeight * scaleFactor;
            float newWidth  = oldWidth * scaleFactor;

            //create a 24bit RGB image
            using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero,
                                                                 (int)newWidth, (int)newHeight, 8,
                                                                 (int)(4 * newWidth), CGColorSpace.CreateDeviceRGB(),
                                                                 CGImageAlphaInfo.PremultipliedFirst))
            {
                RectangleF imageRect = new RectangleF(0, 0, newWidth, newHeight);

                // draw the image

                context.DrawImage(imageRect, originalImage.CGImage);

                //UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage());

                //Das skalierte Bild um 90 Grad drehen

                //UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 1, UIImageOrientation.Right);
                UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 1, orientImg);
                //Das gedrehte Bild neu rendern, höhe und Breite vertauscht um das Seitenverhältniss beizubehalten
                UIGraphics.BeginImageContextWithOptions(new CGSize((float)resizedImage.CGImage.Height, (float)resizedImage.CGImage.Width), true, 1.0f); //TODO: Height und Width sind evtl. vertauscht
                resizedImage.Draw(new CGRect(0, 0, (float)resizedImage.CGImage.Height, (float)resizedImage.CGImage.Width));                             //TODO: Height und Width sind evtl. vertauscht

                var resultImage = UIGraphics.GetImageFromCurrentImageContext();
                UIGraphics.EndImageContext();

                resizedImage = resultImage;

                return(resizedImage.AsJPEG(100).ToArray());

                // save the image as a jpeg
                //return resizedImage.AsJPEG(100).ToArray();
            }
        }
예제 #9
0
        public static void setImage(UIImage i, string s)
        {
            dictionary.Add(s, i);

            // Create full path for image
            string imagePath = imagePathForKey(s);

            // Turn image into JPG/PNG data.
            NSData d = i.AsJPEG(0.5f);

            // Write it to the full path
            NSError error = new NSError(new NSString("ImageSaveError"), 404);
            d.Save(imagePath, NSDataWritingOptions.Atomic, out error);
        }
예제 #10
0
        public async Task<bool> SaveImage(ImageSource img, string imageName)
        {
            var render = new StreamImagesourceHandler();

            image = await render.LoadImageAsync(img);

            var path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            var nomeImagem = Path.Combine(path, imageName);

            NSData imgData = image.AsJPEG();
            NSError erro = null;

            return imgData.Save(nomeImagem, false, out erro);
        }
예제 #11
0
        async Task <byte[]> GetImageAsByteAsync(bool usePNG, int quality, int desiredWidth, int desiredHeight)
        {
            PImage image = null;

            await ImageService.Instance.Config.MainThreadDispatcher.PostAsync(() =>
            {
                if (Control != null)
                {
                    image = Control.Image;
                }
            }).ConfigureAwait(false);

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

            if (desiredWidth != 0 || desiredHeight != 0)
            {
                image = image.ResizeUIImage((double)desiredWidth, (double)desiredHeight, InterpolationMode.Default);
            }

#if __IOS__
            NSData imageData = usePNG ? image.AsPNG() : image.AsJPEG((nfloat)quality / 100f);

            if (imageData == null || imageData.Length == 0)
            {
                return(null);
            }

            var encoded = imageData.ToArray();
            imageData.TryDispose();
            return(encoded);
#elif __MACOS__
            byte[] encoded;
            using (MemoryStream ms = new MemoryStream())
                using (var stream = usePNG ? image.AsPngStream() : image.AsJpegStream(quality))
                {
                    stream.CopyTo(ms);
                    encoded = ms.ToArray();
                }

            if (desiredWidth != 0 || desiredHeight != 0)
            {
                image.TryDispose();
            }

            return(encoded);
#endif
        }
예제 #12
0
        public static byte[] ResizeImageIOS(UIImage originalImage, float width, float height)
        {
            UIImageOrientation orientation = originalImage.Orientation;

            using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero,
                                                                 (int)width, (int)height, 8,
                                                                 4 * (int)width, CGColorSpace.CreateDeviceRGB(),
                                                                 CGImageAlphaInfo.PremultipliedFirst))
            {
                //RectangleF imageRect = new RectangleF(0, 0, width, height);
                //context.DrawImage(imageRect, originalImage.CGImage);
                UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 0, orientation);
                return(resizedImage.AsJPEG().ToArray());
            }
        }
        public byte[] CompressImage(byte[] imageData, float width, float height)
        {
            UIImage sourceImage = ConvertImage(imageData);

            UIImageOrientation orientation = sourceImage.Orientation;

            using (CGBitmapContext cGBitmapContext = new CGBitmapContext(IntPtr.Zero, (int)width, (int)height, 8,
                                                                         4 * (int)width, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedFirst))
            {
                RectangleF imageReact = new RectangleF(0, 0, width, height);

                cGBitmapContext.DrawImage(imageReact, sourceImage.CGImage);

                UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(cGBitmapContext.ToImage(), 0, orientation);

                return(resizedImage.AsJPEG().ToArray());
            }
        }
예제 #14
0
        public async Task <bool> SaveHandheldImageAsync(string filename, ImageSource imageSource)
        {
            NSData imgData  = null;
            var    renderer = new Xamarin.Forms.Platform.iOS.StreamImagesourceHandler();

            UIKit.UIImage photo = await renderer.LoadImageAsync(imageSource);

            var savedImageFilename = GetHandheldImage(filename);
            var directory          = Path.GetDirectoryName(savedImageFilename);

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
                NSFileManager.SetSkipBackupAttribute(directory, true);
            }

            //var isDirectory = true;
            //if(!NSFileManager.DefaultManager.FileExists(directory, ref isDirectory))
            //{
            //    if (!isDirectory)
            //    {
            //        NSFileManager.DefaultManager.CreateDirectory(directory, true, null);
            //        NSFileManager.SetSkipBackupAttribute(directory, true);
            //    }
            //}

            if (Path.GetExtension(filename).ToLower() == ".png")
            {
                imgData = photo.AsPNG();
            }
            else
            {
                imgData = photo.AsJPEG(100);
            }

            bool    success = false;
            NSError err     = null;

            success = await Task.Run(() => imgData.Save(savedImageFilename, NSDataWritingOptions.Atomic, out err));

            return(success);
        }
예제 #15
0
        public byte[] ResizeImage(byte[] ImageData, float fWidth, float fHeight)
        {
            UIImage            originalImage = ImageFromByteArray(ImageData);
            UIImageOrientation orientation   = originalImage.Orientation;

            using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero,
                                                                 (int)fWidth, (int)fHeight, 8,
                                                                 (int)(4 * fWidth), CGColorSpace.CreateDeviceRGB(),
                                                                 CGImageAlphaInfo.PremultipliedFirst))
            {
                CGRect imageRect = new CGRect(0, 0, fWidth, fHeight);

                // draw the image
                context.DrawImage(imageRect, originalImage.CGImage);

                UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 0, orientation);

                // save the image as a jpeg
                return(resizedImage.AsJPEG().ToArray());
            }
        }
예제 #16
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 ());
			}
		}
예제 #17
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);
                    var req = (HttpWebRequest) WebRequest.Create (url);
                    using (var data = image.AsJPEG ()) {
                        req.Method = "PUT";
                        req.ContentLength = (int) 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, (int) data.Length))
                            ums.CopyTo (s);
                    }
                    req.GetResponse ().Dispose ();
                }
                catch {
                    ok = false;
                }
                finally {
                    if (complete != null) {
                        NSRunLoop.Main.InvokeOnMainThread (delegate {
                            complete (ok);
                        });
                    }
                }
            });
        }
예제 #18
0
        public byte[] ResizeImage(byte[] imageData, float width, float height, int quality)
        {
            UIImage originalImage = ImageFromByteArray(imageData);


            float oldWidth    = (float)originalImage.Size.Width;
            float oldHeight   = (float)originalImage.Size.Height;
            float scaleFactor = 0f;

            if (oldWidth > oldHeight)
            {
                scaleFactor = width / oldWidth;
            }
            else
            {
                scaleFactor = height / oldHeight;
            }

            float newHeight = oldHeight * scaleFactor;
            float newWidth  = oldWidth * scaleFactor;

            //create a 24bit RGB image
            using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero,
                                                                 (int)newWidth, (int)newHeight, 8,
                                                                 (int)(4 * newWidth), CGColorSpace.CreateDeviceRGB(),
                                                                 CGImageAlphaInfo.PremultipliedFirst))
            {
                RectangleF imageRect = new RectangleF(0, 0, newWidth, newHeight);

                // draw the image
                context.DrawImage(imageRect, originalImage.CGImage);

                UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage());

                // save the image as a jpeg
                return(resizedImage.AsJPEG((float)quality).ToArray());
            }
        }
예제 #19
0
        public Tuple <System.Drawing.Size, byte[]> ReduceImage(byte[] datas, int maxWidth)
        {
            UIImage originalImage = ImageFromByteArray(datas);

            //原图比较小,不用缩小
            if (originalImage.Size.Width <= maxWidth)
            {
                return(new Tuple <System.Drawing.Size, byte[]>(
                           new System.Drawing.Size()
                {
                    Width = (int)originalImage.Size.Width,
                    Height = (int)originalImage.Size.Height
                }, datas));
            }
            else //按比例缩小
            {
                int width  = maxWidth;
                int height = (int)(width * originalImage.Size.Height / originalImage.Size.Width);

                using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero,
                                                                     width, height, 8,
                                                                     (4 * width), CGColorSpace.CreateDeviceRGB(),
                                                                     CGImageAlphaInfo.PremultipliedFirst))
                {
                    RectangleF imageRect = new RectangleF(0, 0, width, height);

                    // draw the image
                    context.DrawImage(imageRect, originalImage.CGImage);

                    UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 0, originalImage.Orientation);

                    // save the image as a jpeg
                    return(new Tuple <System.Drawing.Size, byte[]>(
                               new System.Drawing.Size(width, height),
                               resizedImage.AsJPEG().ToArray()));
                }
            }
        }
        private void HandleImagePick(UIImage image, string name)
        {
            ClearCurrentlyActive();
            if (image != null)
            {
                if (_maxPixelDimension > 0 && (image.Size.Height > _maxPixelDimension || image.Size.Width > _maxPixelDimension))
                {
                    // resize the image
                    image = image.ImageToFitSize(new CGSize(_maxPixelDimension, _maxPixelDimension));
                }

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

                    var imageStream = new MemoryStream(byteArray, false);
                    _pictureAvailable?.Invoke(imageStream, name);
                }
            }
            else
            {
                _assumeCancelled?.Invoke();
            }

            _picker.DismissViewController(true, () => { });
            _modalHost.NativeModalViewControllerDisappearedOnItsOwn();
        }
        private static Stream GetImageStream(UIImage image, ImageFormatType formatType)
        {
            if (formatType == ImageFormatType.Jpg)
                return image.AsJPEG().AsStream();

            return image.AsPNG().AsStream();
        }
예제 #22
0
		// this function will check if the asset corresponding to the localIdentifier passed in is already in the bugTrap album.
		// If it is, it will update the existing asset and return nil in the callback, otherwise, a new (duplicate) will be created
		// and the localIdentifier of the newly created asset will be returned by the callback

		public async Task<string> UpdateAsset (UIImage updatedSnapshot, string localIdentifier)
		{
			var tcs = new TaskCompletionSource<string> ();

			var collectionLocalIdentifier = await GetAlbumLocalIdentifier();

			if (string.IsNullOrEmpty(collectionLocalIdentifier)) return null;

			// get the bugTrap album
			var bugTrapAlbum = PHAssetCollection.FetchAssetCollections(new [] { collectionLocalIdentifier }, null)?.firstObject as PHAssetCollection;
			if (bugTrapAlbum != null) {

				// if we passed in null for the localIdentifier, we just want to save the image and
				// get a new identifier (most likely being used as the sdk)
				if (string.IsNullOrEmpty(localIdentifier)) {
					return await SaveAsset(updatedSnapshot, bugTrapAlbum, tcs);
				}

				// get the asset for the localIdentifier
				var asset = PHAsset.FetchAssetsUsingLocalIdentifiers(new [] { localIdentifier }, null)?.firstObject as PHAsset;
				if (asset != null) {

					// get all the albums containing this asset
					var containingAssetResults = PHAssetCollection.FetchAssetCollections(asset, PHAssetCollectionType.Album, null);
					if (containingAssetResults != null) {
						
						// check if any of the albums is the bugTrap album.  if the asset is already in the bugTrap album, update the existing asset.
						if (containingAssetResults.Contains(bugTrapAlbum)) {

							// retrieve a PHContentEditingInput object
							asset.RequestContentEditingInput(null, async (input, info) => 

								PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => {
								
								var editAssetOutput = new PHContentEditingOutput (input);
								editAssetOutput.AdjustmentData = new PHAdjustmentData ("io.bugtrap.bugTrap", "1.0.0", NSData.FromString("io.bugtrap.bugTrap"));
								
								var editAssetJpegData = updatedSnapshot.AsJPEG(1);
								editAssetJpegData.Save(editAssetOutput.RenderedContentUrl, true);

								var editAssetRequest = PHAssetChangeRequest.ChangeRequest(asset);
								editAssetRequest.ContentEditingOutput = editAssetOutput;

							}, (success, error) => {

								if (success) {

									if (!tcs.TrySetResult(null)) {
										var ex = new Exception ("UpdateAsset Failed");
										tcs.TrySetException(ex);
										// Log.Error(ex);
									}

								} else if (error != null) {
									// Log.Error("Photos", error);
									if (!tcs.TrySetResult(null)) {
										var ex = new Exception (error.LocalizedDescription);
										tcs.TrySetException(ex);
										// Log.Error(ex);
									}
								}
							}));
									
						} else {// if the asset isn't in the bugTrap album, create a new asset and put it in the album, and leave the original unchanged

							return await SaveAsset(updatedSnapshot, bugTrapAlbum, tcs);

//							string newLocalIdentifier = null;
//
//							PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => {
//
//								// create a new asset from the UIImage updatedSnapshot
//								var createAssetRequest = PHAssetChangeRequest.FromImage(updatedSnapshot);
//
//								// create a request to make changes to the bugTrap album
//								var collectionRequest = PHAssetCollectionChangeRequest.ChangeRequest(bugTrapAlbum);
//
//								// get a reference to the new localIdentifier
//								newLocalIdentifier = createAssetRequest.PlaceholderForCreatedAsset.LocalIdentifier;
//
//								// add the newly created asset to the bugTrap album
//								collectionRequest.AddAssets(new [] { createAssetRequest.PlaceholderForCreatedAsset });
//
//							}, (success, error) => {
//
//								if (success) {
//
//									if (!tcs.TrySetResult(newLocalIdentifier)) {
//										var ex = new Exception ("UpdateAsset Failed");
//										tcs.TrySetException(ex);
//										// Log.Error(ex);
//									}
//
//								} else if (error != null) {
//									// Log.Error("Photos", error);
//									if (!tcs.TrySetResult(null)) {
//										var ex = new Exception (error.LocalizedDescription);
//										tcs.TrySetException(ex);
//										// Log.Error(ex);
//									}
//								}
//							});
						}
					}
				}
			} else { // couldn't find the bugTrap album - user probably deleted it while the app was open

				albumLocalIdentifier = null;

				var identifier = await createAlbumAndSaveLocalIdentifier();

				if (!string.IsNullOrEmpty(identifier)) return await UpdateAsset(updatedSnapshot, localIdentifier);

				if (!tcs.TrySetResult(null)) {
					var ex = new Exception ("UpdateAsset Failed");
					tcs.TrySetException(ex);
					// Log.Error(ex);
				}
			}

			return await tcs.Task;
		}
예제 #23
0
		public static byte[] ByteArrayFromImage(UIImage image, int quality = 50)
		{
			nfloat myQuality = 1.0f;

			if (quality == 0)
				myQuality = 0.0f;
			else
				myQuality = ((nfloat)quality) / ((nfloat)100);

			using (NSData imageData = image.AsJPEG(myQuality))
			{
				Byte[] myByteArray = new Byte[imageData.Length];
				System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, myByteArray, 0, Convert.ToInt32(imageData.Length));
				return myByteArray;
			}
		}
    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 async void UploadImage(UIImage img)
        {
            var hud = new CodeHub.iOS.Utilities.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)
            {
                AlertDialogService.ShowAlert("Error", "Unable to upload image: " + e.Message);
            }
            finally
            {
                hud.Hide();
            }
        }
예제 #26
0
 internal static ImageSource GetImageSourceFromUIImage(UIImage uiImage)
 {
     return uiImage == null ? null : ImageSource.FromStream(() => uiImage.AsJPEG(0.75f).AsStream());
 }
예제 #27
0
		public static string ToBase64(UIImage image){
			return image.AsJPEG().GetBase64EncodedData (NSDataBase64EncodingOptions.None).ToString ();
		}
예제 #28
0
		public async Task<string> UploadImage(UIImage image, string ext)
		{

			var sasurl = await client.InvokeApiAsync<string>("UsersCustom/GetUploadURL/",HttpMethod.Get,null);
			string imageurl = "";

			CloudBlobContainer container = new CloudBlobContainer(new Uri(sasurl));
			//Write operation: write a new blob to the container.
			CloudBlockBlob blob = container.GetBlockBlobReference(CurrentUser.Id + "_" + DateTime.Now.Ticks + "." + ext);
			blob.Properties.ContentType = "image/jpg";
			imageurl =blob.Uri.AbsoluteUri;
			CurrentUser.ImageUrl = imageurl;

			try
			{
				await blob.UploadFromStreamAsync(image.AsJPEG().AsStream());
			}
			catch (Exception e) {
				Console.WriteLine ("Write operation failed for SAS " + sasurl);
				Console.WriteLine ("Additional error information: " + e.Message);
				Console.WriteLine ();
			}

			await UpdateCurrentUser ();

			return imageurl;

		}
예제 #29
0
		static NSUrl SaveToTmp (UIImage img, string fileName)
		{
			var tmp = Path.GetTempPath ();
			string path = Path.Combine (tmp, fileName);

			NSData imageData = img.AsJPEG (0.5f);
			imageData.Save (path, true);

			var url = new NSUrl (path, false);
			return url;
		}
예제 #30
0
 public static Stream GetStream()
 {
     return(input.AsJPEG().AsStream());
 }