Esempio n. 1
0
            public override async Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
            {
                // try to throw on enter
                ThrowIfNeeded(cancellationToken);

                while (current == null)
                {
                    lock (dataLock)
                    {
                        if (data.Count == 0 && receivedAllData && position == length)
                        {
                            return(0);
                        }

                        if (data.Count > 0 && current == null)
                        {
                            current       = data.Peek();
                            currentStream = current.AsStream();
                            break;
                        }
                    }

                    await Task.Delay(50).ConfigureAwait(false);
                }

                // try to throw again before read
                ThrowIfNeeded(cancellationToken);

                var d           = currentStream;
                var bufferCount = Math.Min(count, (int)(d.Length - d.Position));
                var bytesRead   = await d.ReadAsync(buffer, offset, bufferCount, cancellationToken).ConfigureAwait(false);

                // add the bytes read from the pointer to the position
                position += bytesRead;

                // remove the current primary reference if the current position has reached the end of the bytes
                if (d.Position == d.Length)
                {
                    lock (dataLock)
                    {
                        // this is the same object, it was done to make the cleanup
                        data.Dequeue();
                        current?.Dispose();
                        currentStream?.Dispose();
                        current       = null;
                        currentStream = null;
                    }
                }

                return(bytesRead);
            }
Esempio n. 2
0
        public override void LoadTextureStream(Texture t, System.IO.Stream stream)
        {
            NSData         data         = null;
            CGDataProvider dataProvider = null;
            CGImage        image        = null;

            try
            {
                data = NSData.FromStream(stream);
                if (data != null)
                {
                    dataProvider = new CGDataProvider(data);
                    image        = CGImage.FromPNG(dataProvider, null, false, CGColorRenderingIntent.Default);

                    LoadTextureFromImage(t, image);
                }
                else
                {
                    t.Failed = true;
                    return;
                }
            }
            catch (Exception)
            {
                t.Failed = true;
                return;
            }
            finally
            {
                if (dataProvider != null)
                {
                    dataProvider.Dispose();
                }
                if (data != null)
                {
                    data.Dispose();
                }
            }
        }
Esempio n. 3
0
        string Save(UIImage origImage, string name, string documentsDirectory)
        {
            var     compressionQuality = 0.46f;
            string  jpgFilename        = System.IO.Path.Combine(documentsDirectory, name);
            var     resizedImage       = MaxResizeImage(origImage, 1920f, 1080f);
            NSData  imgData            = resizedImage.AsJPEG(compressionQuality);
            NSError err = null;

            if (imgData.Save(jpgFilename, NSDataWritingOptions.Atomic, out err))
            {
                //Dispose of objects.
                origImage.Dispose();
                resizedImage.Dispose();
                imgData.Dispose();
                return(jpgFilename);
            }
            else
            {
                Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
                return(null);
            }
        }
Esempio n. 4
0
        private async Task <byte[]> GetImageAsByteAsync(bool usePNG, int quality, int desiredWidth, int desiredHeight)
        {
            UIImage image = null;

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

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

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

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

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

            var encoded = imageData.ToArray();

            imageData.Dispose();

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

            return(encoded);
        }
        public static byte[] UIImageToBytes(this UIImage image)
        {
            if (image == null)
            {
                return(null);
            }
            NSData data = null;

            try
            {
                data = image.AsPNG();
                return(data.ToArray());
            }
            catch (Exception)
            {
                return(null);
            }
            finally
            {
                image.Dispose();
                data?.Dispose();
            }
        }
Esempio n. 6
0
        public void Save(Stream stream, ImageFormat format)
        {
            NSData data = null;

            switch (format)
            {
            case ImageFormat.Jpeg:
                data = Control.AsJPEG();
                break;

            case ImageFormat.Png:
                data = Control.AsPNG();
                break;

            case ImageFormat.Bitmap:
            case ImageFormat.Gif:
            case ImageFormat.Tiff:
            default:
                throw new NotSupportedException();
            }
            data.AsStream().CopyTo(stream);
            data.Dispose();
        }
Esempio n. 7
0
 public void Cleanup()
 {
     imageUrl?.Dispose();
     imageData?.Dispose();
 }
Esempio n. 8
0
        private UIImage ImageHotel(string imgName, string url)
        {
            try
            {
                UIImage resp;
                string  sCachedPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), imgName);
                resp = UIImage.FromFile(sCachedPath);

                //Console.WriteLine (sCachedPath);


                if (resp == null && url.Length > 0)
                {
                    //Console.WriteLine("No se encontro cache imagenes");

                    NSUrl  imageUrl  = NSUrl.FromString(url);
                    NSData imageData = NSData.FromUrl(imageUrl);

                    if (imageData == null)
                    {
                        return(null);
                    }
                    resp = UIImage.LoadFromData(imageData);                             //   .Add(new BasicTableImageItem(){ Image = new UIImageView (   UIImage.LoadFromData (imageData)).Image , RoomType  =  controller.RoomType});



                    try
                    {
                        NSError err = new NSError(new NSString("http://www.univisit.com"), 0);

                        //InvokeOnMainThread (delegate {

                        int newvalue = 43;

                        if (userMember.parent == "POS" || userMember.isPresentAsCategory)
                        {
                            newvalue = 37;
                        }

                        var res = ResizeImage(resp, newvalue, newvalue).AsPNG().Save(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), imgName), true, out err);
                        if (!res)
                        {
                            Console.WriteLine("Error: " + err.LocalizedDescription);
                        }
                        //	}
                        //	);
                        //01 Jul 2013
                        resp = null;                        //12 Mb
                        imageData.Dispose();
                        imageData = null;
                        resp      = UIImage.FromFile(sCachedPath);
                    }

                    catch (Exception ex) {
                        Console.WriteLine(ex.ToString());
                        return(null);
                    }
                }
                else
                {
                    //  Console.WriteLine("se carga cache imagenes");
                }

                return(resp);
            }
            catch (Exception ex) {
                Console.WriteLine(ex.ToString());

                return(null);
            }
        }
Esempio n. 9
0
        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear(animated);

            // http://stackoverflow.com/questions/7436870/resizing-monotouch-dialog-styledmultilineelement-after-an-async-call
            // NameResolutionFailure on device...
            Util.PushNetworkActive();

            if (_bio.UpdateImage)
            {
                _view.ShowActivity();
            }

            if (!_fetching)
            {
                _fetching = true;
                ThreadPool.QueueUserWorkItem(s =>
                {
                    try
                    {
                        var client = new WebClient();
                        var json   = client.DownloadString(string.Format("https://api.twitter.com/users/show/{0}.json?include_entities=1", _bio.Twitter));
                        var user   = JsonParser.FromJson(json);
                        client.Dispose();

                        // http://a2.twimg.com/profile_images/1558350756/image.jpg
                        // http://a2.twimg.com/profile_images/1558350756/image_normal.jpg
                        //var url = user["profile_image_url"].ToString().Replace("_normal", "_reasonably_small"); // Gets the 128px version
                        var url = user["profile_image_url"].ToString().Replace("_normal", "");                         // Gets the full version

                        // Sometimes Twitter does not return the inline status (this is obviously a bug)
                        string tweet;
                        if (!user.ContainsKey("status"))
                        {
                            tweet = "...";
                        }
                        else
                        {
                            tweet = ((IDictionary <string, object>)user["status"])["text"].ToString();
                        }

                        UIImage image = null;

                        // Update twitter image on disk
                        if (_bio.UpdateImage)
                        {
                            NSUrl imageUrl   = NSUrl.FromString(url);
                            NSData imageData = NSData.FromUrl(imageUrl);

                            image = UIImage.LoadFromData(imageData);
                            image = ImageHelper.RoundAndSquare(image, 14);

                            ImageCache.StoreAs("latest_twitter", image);
                            imageData.Dispose();
                        }
                        else
                        {
                            image = _view.GetDefaultBioImage();
                        }

                        InvokeOnMainThread(() =>
                        {
                            Util.PopNetworkActive();
                            _bio.Image = image;
                            _main.Remove(_tweetBox);
                            CreateTweetView(tweet);
                            _main.Add(_tweetBox);
                            _view.AddOrUpdateBio(_bio);

                            image.Dispose();
                            this.View.SetNeedsDisplay();
                        });
                    }
                    catch
                    {
                    }
                    finally
                    {
                        InvokeOnMainThread(() =>
                        {
                            _view.HideActivity();
                            _fetching = false;
                        });
                    }
                });
            }
        }
Esempio n. 10
0
        //Download and resize image
        public async Task <Stream> DownloadResizeImage(Uri downloadUri, uint maxWidth, uint maxHeight)
        {
            try
            {
                //Check local cache
                Stream imageStream = null;
                string cacheFile   = Path.Combine("Cache", AVFunctions.StringToHash(downloadUri.ToString()));
                if (AVFiles.File_Exists(cacheFile, true))
                {
                    //Load cached image
                    imageStream = AVFiles.File_LoadStream(cacheFile, true);

                    Debug.WriteLine("Apple cache image length: " + imageStream.Length);
                }
                else
                {
                    //Download image
                    imageStream = await AVDownloader.DownloadStreamAsync(8000, null, null, downloadUri);

                    //Save cache image
                    AVFiles.File_SaveStream(cacheFile, imageStream, true, true);

                    Debug.WriteLine("Apple download image length: " + imageStream.Length);
                }

                //Decode image
                if (imageStream.CanSeek)
                {
                    imageStream.Position = 0;
                }
                NSData  imageNsData   = NSData.FromStream(imageStream);
                UIImage originalImage = UIImage.LoadFromData(imageNsData);

                //Calculate size
                uint  resizeWidth    = 0;
                uint  resizeHeight   = 0;
                uint  originalWidth  = (uint)originalImage.Size.Width;
                uint  originalHeight = (uint)originalImage.Size.Height;
                float originalAspect = (float)originalWidth / (float)originalHeight;
                if (originalWidth > maxWidth)
                {
                    resizeWidth  = maxWidth;
                    resizeHeight = (uint)(maxWidth / originalAspect);
                }
                else if (originalHeight > maxHeight)
                {
                    resizeWidth  = (uint)(maxHeight / originalAspect);
                    resizeHeight = maxHeight;
                }
                else
                {
                    resizeWidth  = originalWidth;
                    resizeHeight = originalHeight;
                }
                //Debug.WriteLine("Resizing image to: " + resizeWidth + "w/" + resizeHeight + "h/" + originalAspect + "a");

                //Resize image
                UIGraphics.BeginImageContext(new SizeF(resizeWidth, resizeHeight));
                originalImage.Draw(new RectangleF(0, 0, resizeWidth, resizeHeight));
                UIImage resizeImage = UIGraphics.GetImageFromCurrentImageContext();
                UIGraphics.EndImageContext();

                //Convert stream
                Stream resizeStream = resizeImage.AsPNG().AsStream();

                //Dispose resources
                imageStream.Dispose();
                imageNsData.Dispose();
                originalImage.Dispose();
                resizeImage.Dispose();

                //Return stream
                return(resizeStream);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed to download and resize image: " + ex.Message);
                return(null);
            }
        }