Beispiel #1
0
        UIImage CreateAnimatedImage(byte [] data)
        {
            var imagesOut = new List <UIImage> ();

            var image     = CGImageSource.FromData(NSData.FromArray(data));
            var numImages = image.ImageCount;

            for (int i = 0; i < numImages; i++)
            {
                imagesOut.Add(new UIImage(image.CreateImage(i, null)));
            }

            return(UIImage.CreateAnimatedImage(imagesOut.ToArray(), numImages * .1));
        }
Beispiel #2
0
        public static CBUUID FromBytes(byte [] bytes)
        {
            if (bytes == null)
            {
                throw new ArgumentNullException("bytes");
            }
            else if (bytes.Length != 2 && bytes.Length != 4 && bytes.Length != 16)
            {
                throw new ArgumentException("must either be 2, 4, or 16 bytes long", "bytes");
            }

            using (var data = NSData.FromArray(bytes))
                return(CBUUID.FromData(data));
        }
        public void SetBytes(byte[] bytes, string key)
        {
            if (bytes == null)
            {
                throw new ArgumentNullException(nameof(bytes));
            }

            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            SetData(NSData.FromArray(bytes), key);
        }
        public void SavePictureToDisk(string filename, byte[] imageData)
        {
            var chartImage = new UIImage(NSData.FromArray(imageData));

            chartImage.SaveToPhotosAlbum((image, error) =>
            {
                //you can retrieve the saved UI Image as well if needed using
                //var i = image as UIImage;
                if (error != null)
                {
                    Console.WriteLine(error.ToString());
                }
            });
        }
        /// <summary>
        /// Write the specified data to the characteristic
        /// </summary>
        /// <param name="data">Data.</param>
        public void Write(byte[] data)
        {
            if (!CanWrite)
            {
                throw new InvalidOperationException("Characteristic does not support WRITE");
            }

            var nsData    = NSData.FromArray(data);
            var writeType = ((Properties & CharacteristicPropertyType.AppleWriteWithoutResponse) > 0) ?
                            CBCharacteristicWriteType.WithoutResponse :
                            CBCharacteristicWriteType.WithResponse;

            _peripheral.WriteValue(nsData, _nativeCharacteristic, writeType);
        }
Beispiel #6
0
        protected override void Initialize()
        {
            // the following code relies on SensusServiceHelper singleton, which will not be available above in the constructor.

            // create device id characteristic
            _deviceIdCharacteristic = new CBMutableCharacteristic(CBUUID.FromString(DEVICE_ID_CHARACTERISTIC_UUID),
                                                                  CBCharacteristicProperties.Read,
                                                                  NSData.FromArray(Encoding.UTF8.GetBytes(SensusServiceHelper.Get().DeviceId)),
                                                                  CBAttributePermissions.Readable);

            // create service with device id characteristic
            _deviceIdService = new CBMutableService(CBUUID.FromString(DEVICE_ID_SERVICE_UUID), true);
            _deviceIdService.Characteristics = new CBCharacteristic[] { _deviceIdCharacteristic };
        }
Beispiel #7
0
        public Task <bool> WriteAsync(byte[] buffer, int offset, int count)
        {
            try
            {
                _peripheral.WriteValue(NSData.FromArray(buffer), new CBMutableDescriptor(_peripheral.UUID, _peripheral.Self));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(Task.FromResult(false));
            }

            return(Task.FromResult(true));
        }
Beispiel #8
0
 public Task <byte[]> NormalizeAsync(byte[] imageData, float quality)
 {
     return(Task <byte[]> .Factory.StartNew(delegate {
         UIImage img = UIImage.LoadFromData(NSData.FromArray(imageData));
         if (img.Orientation != UIImageOrientation.Up)
         {
             UIGraphics.BeginImageContextWithOptions(img.Size, false, 1);
             img.Draw(new CGRect(0, 0, img.Size.Width, img.Size.Height));
             img = UIGraphics.GetImageFromCurrentImageContext();
             UIGraphics.EndImageContext();
         }
         return (img.AsJPEG(quality).ToArray());
     }));
 }
 public PhotoListViewController()
 {
     this.WhenActivated(d =>
     {
         d(ViewModel.WhenAnyValue(vm => vm.LoadedPhotoData)
           .Where(data => data != null)
           .Select(data => data.Select(p => new UIImage(NSData.FromArray(p))))
           .Do(i => Images = i.ToArray())
           .Do(i => Photos.ReloadData())
           .Subscribe());
         d(this.BindCommand(ViewModel, vm => vm.Share, view => view.Share));
         ViewModel.LoadPhotos.Execute(null);
     });
 }
Beispiel #10
0
 public override NSObject ContentsForType(string typeName, out NSError outError)
 {
     try {
         var bytes = Encoding.GetBytes(Code);
         var data  = NSData.FromArray(bytes);
         outError = null;
         return(data);
     }
     catch (Exception ex) {
         Debug.WriteLine(ex);
         outError = NSError.FromDomain(new NSString("CEditor"), 1002);
         return(null);
     }
 }
Beispiel #11
0
        /// <summary>
        /// Decodes the specified bytes as an image.
        /// </summary>
        /// <param name="bytes">Byte array that contains a WebP image.</param>
        public UIImage Decode(byte[] bytes)
        {
            NSError error = null;

            using (var data = NSData.FromArray(bytes))
            {
                var result = _decoder.ImageWithWebPData(data, out error);
                if (error != null)
                {
                    throw new NSErrorException(error);
                }
                return(result);
            }
        }
Beispiel #12
0
 /// <summary>
 /// Tracks revenue with product identifier and optional transaction receipt.
 /// </summary>
 public void LogRevenue(string productIdentifier, int quantity, double price, byte[] receipt = null)
 {
     if (receipt != null)
     {
         _native?.LogRevenue(productIdentifier, (nint)quantity,
                             NSNumber.FromDouble(price),
                             NSData.FromArray(receipt));
     }
     else
     {
         _native?.LogRevenue(productIdentifier, (nint)quantity,
                             NSNumber.FromDouble(price));
     }
 }
Beispiel #13
0
        public async Task <UIImage> LoadImage(string imageUrl)
        {
            BTProgressHUD.Show("Descargando imagen");

            var httpClient = new HttpClient();

            Task <byte[]> contentsTask = httpClient.GetByteArrayAsync(imageUrl);

            // await! control returns to the caller and the task continues to run on another thread
            var contents = await contentsTask;

            // load from bytes
            return(UIImage.LoadFromData(NSData.FromArray(contents)));
        }
Beispiel #14
0
        protected override async Task InitializeAsync()
        {
            await base.InitializeAsync();

            // create device id characteristic
            _deviceIdCharacteristic = new CBMutableCharacteristic(CBUUID.FromString(DEVICE_ID_CHARACTERISTIC_UUID),
                                                                  CBCharacteristicProperties.Read,
                                                                  NSData.FromArray(Encoding.UTF8.GetBytes(SensusServiceHelper.Get().DeviceId)),
                                                                  CBAttributePermissions.Readable);

            // create service with device id characteristic
            _deviceIdService = new CBMutableService(CBUUID.FromString(Protocol.Id), true);
            _deviceIdService.Characteristics = new CBCharacteristic[] { _deviceIdCharacteristic };
        }
Beispiel #15
0
        public static async Task <UIImage> LoadImageAsync(string imageUrl)
        {
            if (string.IsNullOrEmpty(imageUrl))
            {
                return(UIImage.FromBundle("DefaultAvator"));
            }

            var httpClient = new HttpClient();

            byte[] contents = await httpClient.GetByteArrayAsync(imageUrl);

            // load from bytes
            return(UIImage.LoadFromData(NSData.FromArray(contents)));
        }
Beispiel #16
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var headers = request.Headers as IEnumerable <KeyValuePair <string, IEnumerable <string> > >;
            var ms      = new MemoryStream();

            if (request.Content != null)
            {
                await request.Content.CopyToAsync(ms).ConfigureAwait(false);

                headers = headers.Union(request.Content.Headers).ToArray();
            }

            var rq = new NSMutableUrlRequest()
            {
                AllowsCellularAccess = true,
                Body        = NSData.FromArray(ms.ToArray()),
                CachePolicy = (!this.DisableCaching ? NSUrlRequestCachePolicy.UseProtocolCachePolicy : NSUrlRequestCachePolicy.ReloadIgnoringCacheData),
                Headers     = headers.Aggregate(new NSMutableDictionary(), (acc, x) =>
                {
                    acc.Add(new NSString(x.Key), new NSString(String.Join(getHeaderSeparator(x.Key), x.Value)));
                    return(acc);
                }),
                HttpMethod = request.Method.ToString().ToUpperInvariant(),
                Url        = NSUrl.FromString(request.RequestUri.AbsoluteUri),
            };

            var op = session.CreateDataTask(rq);

            cancellationToken.ThrowIfCancellationRequested();

            var ret = new TaskCompletionSource <HttpResponseMessage>();

            cancellationToken.Register(() => ret.TrySetCanceled());

            lock (inflightRequests)
            {
                inflightRequests[op] = new InflightOperation()
                {
                    FutureResponse    = ret,
                    Request           = request,
                    Progress          = getAndRemoveCallbackFromRegister(request),
                    ResponseBody      = new ByteArrayListStream(),
                    CancellationToken = cancellationToken,
                };
            }

            op.Resume();
            return(await ret.Task.ConfigureAwait(false));
        }
        private SecRecord NewSecRecord(string alias, byte[] data)
        {
            var secRecord = new SecRecord(SecKind.GenericPassword)
            {
                Account = alias,
                Service = StorageIdentity,
                Label   = alias
            };

            if (data != null && data.Length > 0)
            {
                secRecord.ValueData = NSData.FromArray(data);
            }
            return(secRecord);
        }
Beispiel #18
0
        /// <summary>
        /// Initiates a navigate request to the provided URI. This method allows customizable options for including posted form data and HTTP headers.
        /// </summary>
        /// <param name="uri">The URI to navigate to.</param>
        /// <param name="postData">The posted form data.</param>
        /// <param name="additionalHeaders">The additional HTTP headers.</param>
        public void Navigate(Uri uri, byte[] postData, string additionalHeaders)
        {
            var request = new NSMutableUrlRequest(UriToNsUrl(uri));

            if (postData != null && postData.Length != 0)
            {
                request.Body = NSData.FromArray(postData);
            }
            if (!string.IsNullOrEmpty(additionalHeaders))
            {
                request.Headers = ParceAdditionalHeaders(additionalHeaders);
            }

            this.NativeWebView.LoadRequest(request);
        }
        public override void WriteCharacteristic(object characteristic, byte[] value, bool isReliable)
        {
            CBCharacteristic c = characteristic as CBCharacteristic;
            if (c == null)
                return;

            if (isReliable)
            {
                Peripheral.WriteValue(NSData.FromArray(value), c, CBCharacteristicWriteType.WithResponse);
            }
            else
            {
                Peripheral.WriteValue(NSData.FromArray(value), c, CBCharacteristicWriteType.WithoutResponse);
            }
        }
Beispiel #20
0
        public void Write(byte[] data)
        {
            if (!CanWrite)
            {
                throw new InvalidOperationException("Characteristic does not support WRITE");
            }
            var nsdata     = NSData.FromArray(data);
            var descriptor = (CBCharacteristic)nativeCharacteristic;
            var t          = (Properties & CharacteristicPropertyType.AppleWriteWithoutResponse) != 0 ?
                             CBCharacteristicWriteType.WithoutResponse :
                             CBCharacteristicWriteType.WithResponse;

            parentDevice.WriteValue(nsdata, descriptor, t);
            return;
        }
Beispiel #21
0
        public IBitmap Load(Stream stream)
        {
            byte[] buffer = new byte[stream.Length];
            stream.Read(buffer, 0, buffer.Length);
            using (NSData data = NSData.FromArray(buffer))
            {
                UIImage image = UIImage.LoadFromData(data);

                //For some reason, flipping the image vertically is required for IOS, see Alexey Podlasov's answer here: http://stackoverflow.com/questions/5404706/how-to-flip-uiimage-horizontally
                //todo: maybe instead of flipping the image at run-time we can flip it at compile-time for ios
                image = flipVertically(image);

                return(new IOSBitmap(image, _graphics));
            }
        }
Beispiel #22
0
 private Bitmap(SerializationInfo info, StreamingContext context)
 {
     foreach (SerializationEntry serEnum in info)
     {
         if (String.Compare(serEnum.Name, "Data", true) == 0)
         {
             byte[] bytes = (byte[])serEnum.Value;
             if (bytes != null && bytes.Length > 0)
             {
                 imageSource = CGImageSource.FromData(NSData.FromArray(bytes));
                 InitializeImageFrame(0);
             }
         }
     }
 }
        public async Task Classify(byte[] bytes)
        {
            var modelUrl      = NSBundle.MainBundle.GetUrlForResource("model", "mlmodel");
            var compiledUrl   = MLModel.CompileModel(modelUrl, out var error);
            var compiledModel = MLModel.Create(compiledUrl, out error);

            var vnCoreModel = VNCoreMLModel.FromMLModel(compiledModel, out error);

            var classificationRequest = new VNCoreMLRequest(vnCoreModel, HandleVNRequest);

            var data    = NSData.FromArray(bytes);
            var handler = new VNImageRequestHandler(data, CGImagePropertyOrientation.Up, new VNImageOptions());

            handler.Perform(new[] { classificationRequest }, out error);
        }
Beispiel #24
0
        public void SaveImage(string path, byte[] byteArray)
        {
            File.WriteAllBytes(path, byteArray);

            NSData data = NSData.FromArray(byteArray);

            //Save dans l'album, utile pour le debug.

            /*var someImage = UIImage.LoadFromData(data);
             * someImage.SaveToPhotosAlbum((image, error) =>
             * {
             *      var o = image as UIImage;
             *      Console.WriteLine("error:" + error);
             * });*/
        }
        private const uint KeyLength             = 32; // 256 bit

        public byte[] DeriveKey(byte[] password, byte[] salt, uint rounds)
        {
            var passwordData = NSData.FromArray(password);
            var saltData     = NSData.FromArray(salt);

            var keyData = new NSMutableData();

            keyData.Length = KeyLength;
            var result = CCKeyCerivationPBKDF(PBKDFAlgorithm, passwordData.Bytes, passwordData.Length, saltData.Bytes,
                                              saltData.Length, PseudoRandomAlgorithm, rounds, keyData.MutableBytes, keyData.Length);

            byte[] keyBytes = new byte[keyData.Length];
            Marshal.Copy(keyData.Bytes, keyBytes, 0, Convert.ToInt32(keyData.Length));
            return(keyBytes);
        }
Beispiel #26
0
 public void UpdateCell(OrderItem item)
 {
     this.NameLabel.Text   = item.Name;
     this.OrderImage.Image = UIImage.LoadFromData(NSData.FromArray(item.Picture.Pic));
     if (item.Derived)
     {
         this.StatusLabel.Text      = "Доставленно";
         this.StatusLabel.TextColor = UIColor.Green;
     }
     else
     {
         this.StatusLabel.Text      = "В пути";
         this.StatusLabel.TextColor = UIColor.Red;
     }
 }
Beispiel #27
0
        async public void SavePictureToDisk(string filename, Task <byte[]> imageData)
        {
            NSData data       = NSData.FromArray(await imageData);
            var    chartImage = new UIImage(data);

            chartImage.SaveToPhotosAlbum((image, error) =>
            {
                //you can retrieve the saved UI Image as well if needed using
                //var i = image as UIImage;
                if (error != null)
                {
                    System.Diagnostics.Debug.WriteLine(error.ToString());
                }
            });
        }
Beispiel #28
0
        /// <exception cref="FailedToParsePlist"></exception>
        public static NSDictionary PayloadToNSDictionary(byte[] payload)
        {
            var plistData = NSData.FromArray(payload);
            var format    = NSPropertyListFormat.Xml;

            NSError error;
            var     ret = (NSDictionary)NSPropertyListSerialization.PropertyListWithData(plistData, ref format, out error);

            if (ret == null)
            {
                throw new FailedToParsePlist();
            }

            return(ret);
        }
Beispiel #29
0
 public static UIImage ImageFromBytes(byte[] bytes, nfloat width, nfloat height)
 {
     try {
         NSData  data      = NSData.FromArray(bytes);
         UIImage image     = UIImage.LoadFromData(data);
         CGSize  scaleSize = new CGSize(width, height);
         UIGraphics.BeginImageContextWithOptions(scaleSize, false, 0);
         image.Draw(new CGRect(0, 0, scaleSize.Width, scaleSize.Height));
         UIImage resizedImage = UIGraphics.GetImageFromCurrentImageContext();
         UIGraphics.EndImageContext();
         return(resizedImage);
     } catch (Exception) {
         return(null);
     }
 }
        void FillScreen()
        {
            this.MemberNameLbl.Text       = viewModel.Member.Name;
            this.MemberReputationLbl.Text = viewModel.Member.Reputation;
            this.ArticleCountLbl.Text     = "Articles: " + viewModel.Member.ArticleCount;
            this.AvgArticleRatingLbl.Text = "Average article rating: " + viewModel.Member.AverageArticleRating;
            this.BlogCountLbl.Text        = "Blogs: " + viewModel.Member.BlogCount;
            this.AvgBlogRatingLbl.Text    = "Average blog rating: " + viewModel.Member.AverageBlogRating;

            if (viewModel.Member.Avatar != null)
            {
                NSData data = NSData.FromArray(viewModel.Member.Avatar);
                this.MemberImage.Image = UIImage.LoadFromData(data, 1);
            }
        }