Beispiel #1
0
 private UIImage DecodeStream(Stream stream)
 {
     return(UIImage.LoadFromData(NSData.FromStream(stream)));
 }
        protected async override Task <UIImage> GenerateImageAsync(string path, ImageSource source, Stream imageData, ImageInformation imageInformation, bool enableTransformations, bool isPlaceholder)
        {
            UIImage imageIn = null;

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

            ThrowIfCancellationRequested();

            try
            {
                // Special case to handle WebP decoding on iOS

                string ext = null;
                if (!string.IsNullOrWhiteSpace(path))
                {
                    if (source == ImageSource.Url)
                    {
                        ext = Path.GetExtension(new Uri(path).LocalPath).ToLowerInvariant();
                    }
                    else
                    {
                        ext = Path.GetExtension(path).ToLowerInvariant();
                    }
                }

                if (source != ImageSource.Stream && ext == ".webp")
                {
                    imageIn = new WebP.Touch.WebPCodec().Decode(imageData);
                }
                // Special case to handle gif animations on iOS
                else if (source != ImageSource.Stream && ext == ".gif")
                {
                    using (var nsdata = NSData.FromStream(imageData))
                        imageIn = GifHelper.AnimateGif(nsdata);
                }
                else
                {
                    var nsdata           = NSData.FromStream(imageData);
                    int downsampleWidth  = Parameters.DownSampleSize?.Item1 ?? 0;
                    int downsampleHeight = Parameters.DownSampleSize?.Item2 ?? 0;

                    if (Parameters.DownSampleUseDipUnits)
                    {
                        downsampleWidth  = downsampleWidth.PointsToPixels();
                        downsampleHeight = downsampleHeight.PointsToPixels();
                    }

                    imageIn = nsdata.ToImage(new CoreGraphics.CGSize(downsampleWidth, downsampleHeight), ScaleHelper.Scale, NSDataExtensions.RCTResizeMode.ScaleAspectFill, imageInformation);
                }
            }
            finally
            {
                imageData?.Dispose();
            }

            ThrowIfCancellationRequested();

            if (enableTransformations && Parameters.Transformations != null && Parameters.Transformations.Count > 0)
            {
                var transformations = Parameters.Transformations.ToList();

                await _decodingLock.WaitAsync().ConfigureAwait(false); // Applying transformations is both CPU and memory intensive

                try
                {
                    foreach (var transformation in transformations)
                    {
                        ThrowIfCancellationRequested();

                        var old = imageIn;

                        try
                        {
                            var bitmapHolder = transformation.Transform(new BitmapHolder(imageIn), path, source, isPlaceholder, Key);
                            imageIn = bitmapHolder.ToNative();
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(string.Format("Transformation failed: {0}", transformation.Key), ex);
                            throw;
                        }
                        finally
                        {
                            if (old != null && old != imageIn && old.Handle != imageIn.Handle)
                            {
                                old.Dispose();
                            }
                        }
                    }
                }
                finally
                {
                    _decodingLock.Release();
                }
            }

            return(imageIn);
        }
Beispiel #3
0
 public void FromStream_CanNotRead()
 {
     using (var s = new CanNotReadStream()) {
         Assert.Null(NSData.FromStream(s), "!CanRead");
     }
 }
Beispiel #4
0
        // almost identical to ModernHttpClient version but it uses the constants from monotouch.dll | Xamarin.[iOS|WatchOS|TVOS].dll
        static Exception createExceptionForNSError(NSError error)
        {
            // var webExceptionStatus = WebExceptionStatus.UnknownError;

            var innerException = new NSErrorException(error);

            // errors that exists in both share the same error code, so we can use a single switch/case
            // this also ease watchOS integration as if does not expose CFNetwork but (I would not be
            // surprised if it)could return some of it's error codes
#if __WATCHOS__
            if (error.Domain == NSError.NSUrlErrorDomain)
            {
#else
            if ((error.Domain == NSError.NSUrlErrorDomain) || (error.Domain == NSError.CFNetworkErrorDomain))
            {
#endif
                // Parse the enum into a web exception status or exception. Some
                // of these values don't necessarily translate completely to
                // what WebExceptionStatus supports, so made some best guesses
                // here.  For your reading pleasure, compare these:
                //
                // Apple docs: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/index.html#//apple_ref/doc/constant_group/URL_Loading_System_Error_Codes
                // .NET docs: http://msdn.microsoft.com/en-us/library/system.net.webexceptionstatus(v=vs.110).aspx
                switch ((NSUrlError)(long)error.Code)
                {
                case NSUrlError.Cancelled:
                case NSUrlError.UserCancelledAuthentication:
#if !__WATCHOS__
                case (NSUrlError)NSNetServicesStatus.CancelledError:
#endif
                    // No more processing is required so just return.
                    return(new OperationCanceledException(error.LocalizedDescription, innerException));
//              case NSUrlError.BadURL:
//              case NSUrlError.UnsupportedURL:
//              case NSUrlError.CannotConnectToHost:
//              case NSUrlError.ResourceUnavailable:
//              case NSUrlError.NotConnectedToInternet:
//              case NSUrlError.UserAuthenticationRequired:
//              case NSUrlError.InternationalRoamingOff:
//              case NSUrlError.CallIsActive:
//              case NSUrlError.DataNotAllowed:
// #if !__WATCHOS__
//              case (NSUrlError) CFNetworkErrors.Socks5BadCredentials:
//              case (NSUrlError) CFNetworkErrors.Socks5UnsupportedNegotiationMethod:
//              case (NSUrlError) CFNetworkErrors.Socks5NoAcceptableMethod:
//              case (NSUrlError) CFNetworkErrors.HttpAuthenticationTypeUnsupported:
//              case (NSUrlError) CFNetworkErrors.HttpBadCredentials:
//              case (NSUrlError) CFNetworkErrors.HttpBadURL:
// #endif
//                  webExceptionStatus = WebExceptionStatus.ConnectFailure;
//                  break;
//              case NSUrlError.TimedOut:
// #if !__WATCHOS__
//              case (NSUrlError) CFNetworkErrors.NetServiceTimeout:
// #endif
//                  webExceptionStatus = WebExceptionStatus.Timeout;
//                  break;
//              case NSUrlError.CannotFindHost:
//              case NSUrlError.DNSLookupFailed:
// #if !__WATCHOS__
//              case (NSUrlError) CFNetworkErrors.HostNotFound:
//              case (NSUrlError) CFNetworkErrors.NetServiceDnsServiceFailure:
// #endif
//                  webExceptionStatus = WebExceptionStatus.NameResolutionFailure;
//                  break;
//              case NSUrlError.DataLengthExceedsMaximum:
//                  webExceptionStatus = WebExceptionStatus.MessageLengthLimitExceeded;
//                  break;
//              case NSUrlError.NetworkConnectionLost:
// #if !__WATCHOS__
//              case (NSUrlError) CFNetworkErrors.HttpConnectionLost:
// #endif
//                  webExceptionStatus = WebExceptionStatus.ConnectionClosed;
//                  break;
//              case NSUrlError.HTTPTooManyRedirects:
//              case NSUrlError.RedirectToNonExistentLocation:
// #if !__WATCHOS__
//              case (NSUrlError) CFNetworkErrors.HttpRedirectionLoopDetected:
// #endif
//                  webExceptionStatus = WebExceptionStatus.ProtocolError;
//                  break;
//              case NSUrlError.RequestBodyStreamExhausted:
// #if !__WATCHOS__
//              case (NSUrlError) CFNetworkErrors.SocksUnknownClientVersion:
//              case (NSUrlError) CFNetworkErrors.SocksUnsupportedServerVersion:
//              case (NSUrlError) CFNetworkErrors.HttpParseFailure:
// #endif
//                  webExceptionStatus = WebExceptionStatus.SendFailure;
//                  break;
//              case NSUrlError.BadServerResponse:
//              case NSUrlError.ZeroByteResource:
//              case NSUrlError.CannotDecodeRawData:
//              case NSUrlError.CannotDecodeContentData:
//              case NSUrlError.CannotParseResponse:
//              case NSUrlError.FileDoesNotExist:
//              case NSUrlError.FileIsDirectory:
//              case NSUrlError.NoPermissionsToReadFile:
//              case NSUrlError.CannotLoadFromNetwork:
//              case NSUrlError.CannotCreateFile:
//              case NSUrlError.CannotOpenFile:
//              case NSUrlError.CannotCloseFile:
//              case NSUrlError.CannotWriteToFile:
//              case NSUrlError.CannotRemoveFile:
//              case NSUrlError.CannotMoveFile:
//              case NSUrlError.DownloadDecodingFailedMidStream:
//              case NSUrlError.DownloadDecodingFailedToComplete:
// #if !__WATCHOS__
//              case (NSUrlError) CFNetworkErrors.Socks4RequestFailed:
//              case (NSUrlError) CFNetworkErrors.Socks4IdentdFailed:
//              case (NSUrlError) CFNetworkErrors.Socks4IdConflict:
//              case (NSUrlError) CFNetworkErrors.Socks4UnknownStatusCode:
//              case (NSUrlError) CFNetworkErrors.Socks5BadState:
//              case (NSUrlError) CFNetworkErrors.Socks5BadResponseAddr:
//              case (NSUrlError) CFNetworkErrors.CannotParseCookieFile:
//              case (NSUrlError) CFNetworkErrors.NetServiceUnknown:
//              case (NSUrlError) CFNetworkErrors.NetServiceCollision:
//              case (NSUrlError) CFNetworkErrors.NetServiceNotFound:
//              case (NSUrlError) CFNetworkErrors.NetServiceInProgress:
//              case (NSUrlError) CFNetworkErrors.NetServiceBadArgument:
//              case (NSUrlError) CFNetworkErrors.NetServiceInvalid:
// #endif
//                  webExceptionStatus = WebExceptionStatus.ReceiveFailure;
//                  break;
//              case NSUrlError.SecureConnectionFailed:
//                  webExceptionStatus = WebExceptionStatus.SecureChannelFailure;
//                  break;
//              case NSUrlError.ServerCertificateHasBadDate:
//              case NSUrlError.ServerCertificateHasUnknownRoot:
//              case NSUrlError.ServerCertificateNotYetValid:
//              case NSUrlError.ServerCertificateUntrusted:
//              case NSUrlError.ClientCertificateRejected:
//              case NSUrlError.ClientCertificateRequired:
//                  webExceptionStatus = WebExceptionStatus.TrustFailure;
//                  break;
// #if !__WATCHOS__
//              case (NSUrlError) CFNetworkErrors.HttpProxyConnectionFailure:
//              case (NSUrlError) CFNetworkErrors.HttpBadProxyCredentials:
//              case (NSUrlError) CFNetworkErrors.PacFileError:
//              case (NSUrlError) CFNetworkErrors.PacFileAuth:
//              case (NSUrlError) CFNetworkErrors.HttpsProxyConnectionFailure:
//              case (NSUrlError) CFNetworkErrors.HttpsProxyFailureUnexpectedResponseToConnectMethod:
//                  webExceptionStatus = WebExceptionStatus.RequestProhibitedByProxy;
//                  break;
// #endif
                }
            }

            // Always create a WebException so that it can be handled by the client.
            return(new WebException(error.LocalizedDescription, innerException));            //, webExceptionStatus, response: null);
        }

        string GetHeaderSeparator(string name)
        {
            string value;

            if (!headerSeparators.TryGetValue(name, out value))
            {
                value = ",";
            }
            return(value);
        }

        async Task <NSUrlRequest> CreateRequest(HttpRequestMessage request)
        {
            var stream  = Stream.Null;
            var headers = request.Headers as IEnumerable <KeyValuePair <string, IEnumerable <string> > >;

            if (request.Content != null)
            {
                stream = await request.Content.ReadAsStreamAsync().ConfigureAwait(false);

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

            var nsrequest = new NSMutableUrlRequest {
                AllowsCellularAccess = allowsCellularAccess,
                CachePolicy          = DisableCaching ? NSUrlRequestCachePolicy.ReloadIgnoringCacheData : NSUrlRequestCachePolicy.UseProtocolCachePolicy,
                HttpMethod           = request.Method.ToString().ToUpperInvariant(),
                Url     = NSUrl.FromString(request.RequestUri.AbsoluteUri),
                Headers = headers.Aggregate(new NSMutableDictionary(), (acc, x) => {
                    acc.Add(new NSString(x.Key), new NSString(string.Join(GetHeaderSeparator(x.Key), x.Value)));
                    return(acc);
                })
            };

            if (stream != Stream.Null)
            {
                // HttpContent.TryComputeLength is `protected internal` :-( but it's indirectly called by headers
                var length = request.Content.Headers.ContentLength;
                if (length.HasValue && (length <= MaxInputInMemory))
                {
                    nsrequest.Body = NSData.FromStream(stream);
                }
                else
                {
                    nsrequest.BodyStream = new WrappedNSInputStream(stream);
                }
            }
            return(nsrequest);
        }
Beispiel #5
0
        /// <summary>
        /// Reads given Stream and decodes it as an image.
        /// </summary>
        /// <param name="stream">A readable Stream that contains a WebP image.</param>
        /// <returns>An image</returns>
        public UIImage Decode(Stream stream)
        {
            var data = NSData.FromStream(stream);

            return(_decoder.ImageWithWebPData(data));
        }
 public override void AddMultipartData(string name, System.IO.Stream data, string mimeType, string filename)
 {
     request.AddMultipartData(NSData.FromStream(data), name, mimeType, string.Empty);
 }
Beispiel #7
0
 public void Create(Stream stream)
 {
     Control = new UIImage(NSData.FromStream(stream));
 }
        public static async Task <NSData> GetImageData(string email, int size, Rating rating = Rating.PG)
        {
            byte[] data = await GetImageBytes(email, size, rating);

            return(NSData.FromStream(new System.IO.MemoryStream(data)));
        }
        protected async override Task <PImage> GenerateImageAsync(string path, ImageSource source, Stream imageData, ImageInformation imageInformation, bool enableTransformations, bool isPlaceholder)
        {
            PImage imageIn = null;

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

            ThrowIfCancellationRequested();

            try
            {
                int  downsampleWidth  = Parameters.DownSampleSize?.Item1 ?? 0;
                int  downsampleHeight = Parameters.DownSampleSize?.Item2 ?? 0;
                bool allowUpscale     = Parameters.AllowUpscale ?? Configuration.AllowUpscale;

                if (Parameters.DownSampleUseDipUnits)
                {
                    downsampleWidth  = downsampleWidth.PointsToPixels();
                    downsampleHeight = downsampleHeight.PointsToPixels();
                }

                // Special case to handle WebP decoding on iOS
                if (source != ImageSource.Stream && imageInformation.Type == ImageInformation.ImageType.WEBP)
                {
#if __IOS__
                    await _webpLock.WaitAsync(CancellationTokenSource.Token).ConfigureAwait(false);

                    ThrowIfCancellationRequested();
                    try
                    {
                        var decoder = _webpDecoder as WebP.Touch.WebPCodec;
                        if (decoder == null)
                        {
                            decoder      = new WebP.Touch.WebPCodec();
                            _webpDecoder = decoder;
                        }
                        var decodedWebP = decoder.Decode(imageData);
                        //TODO Add WebP images downsampling!
                        imageIn = decodedWebP;
                    }
                    finally
                    {
                        _webpLock.Release();
                    }
#else
                    throw new NotImplementedException();
#endif
                }
                else
                {
                    var nsdata = NSData.FromStream(imageData);
                    imageIn = nsdata.ToImage(new CoreGraphics.CGSize(downsampleWidth, downsampleHeight), ScaleHelper.Scale, Configuration, Parameters, NSDataExtensions.RCTResizeMode.ScaleAspectFill, imageInformation, allowUpscale);
                }
            }
            finally
            {
                imageData.TryDispose();
            }

            ThrowIfCancellationRequested();

            if (enableTransformations && Parameters.Transformations != null && Parameters.Transformations.Count > 0)
            {
                var transformations = Parameters.Transformations.ToList();

                await _decodingLock.WaitAsync(CancellationTokenSource.Token).ConfigureAwait(false); // Applying transformations is both CPU and memory intensive

                ThrowIfCancellationRequested();

                try
                {
                    bool isAnimation = false;
#if __IOS__
                    if (imageIn.Images != null)
                    {
                        isAnimation = true;
                    }
#endif
                    if (!isAnimation)
                    {
                        foreach (var transformation in transformations)
                        {
                            ThrowIfCancellationRequested();

                            var old = imageIn;

                            try
                            {
                                var bitmapHolder = transformation.Transform(new BitmapHolder(imageIn), path, source, isPlaceholder, Key);
                                imageIn = bitmapHolder.ToNative();
                            }
                            catch (Exception ex)
                            {
                                Logger.Error(string.Format("Transformation failed: {0}", transformation.Key), ex);
                                throw;
                            }
                            finally
                            {
                                if (old != null && old != imageIn && old.Handle != imageIn.Handle)
                                {
                                    old.TryDispose();
                                }
                            }
                        }
                    }
                    else
                    {
                        // no animted image support for mac implemented
#if __IOS__
                        var animatedImages = imageIn.Images.ToArray();

                        for (int i = 0; i < animatedImages.Length; i++)
                        {
                            var tempImage = animatedImages[i];

                            if (tempImage.CGImage == null)
                            {
                                continue;
                            }

                            foreach (var transformation in transformations)
                            {
                                ThrowIfCancellationRequested();

                                var old = tempImage;

                                try
                                {
                                    var bitmapHolder = transformation.Transform(new BitmapHolder(tempImage), path, source, isPlaceholder, Key);
                                    tempImage = bitmapHolder.ToNative();
                                }
                                catch (Exception ex)
                                {
                                    Logger.Error(string.Format("Transformation failed: {0}", transformation.Key), ex);
                                    throw;
                                }
                                finally
                                {
                                    if (old != null && old != tempImage && old.Handle != tempImage.Handle)
                                    {
                                        old.TryDispose();
                                    }
                                }
                            }

                            animatedImages[i] = tempImage;
                        }

                        var oldImageIn = imageIn;
                        imageIn = PImage.CreateAnimatedImage(animatedImages.Where(v => v.CGImage != null).ToArray(), imageIn.Duration);
                        oldImageIn.TryDispose();
#endif
                    }
                }
                finally
                {
                    _decodingLock.Release();
                }
            }

            return(imageIn);
        }
Beispiel #10
0
        public async Task <IImageSourceServiceResult <UIImage>?> GetImageAsync(IUriImageSource imageSource, float scale = 1, CancellationToken cancellationToken = default)
        {
            if (imageSource.IsEmpty)
            {
                return(null);
            }

            try
            {
                var hash             = Crc64.ComputeHashString(imageSource.Uri.OriginalString);
                var pathToImageCache = CacheDirectory + hash + ".png";

                NSData?imageData;

                if (imageSource.CachingEnabled && IsImageCached(pathToImageCache))
                {
                    imageData = GetCachedImage(pathToImageCache);
                }
                else
                {
                    // TODO: use a real caching library with the URI
                    if (imageSource is not IStreamImageSource streamImageSource)
                    {
                        return(null);
                    }

                    using var stream = await streamImageSource.GetStreamAsync(cancellationToken).ConfigureAwait(false);

                    if (stream == null)
                    {
                        throw new InvalidOperationException($"Unable to load image stream from URI '{imageSource.Uri}'.");
                    }

                    imageData = NSData.FromStream(stream);

                    if (imageData == null)
                    {
                        throw new InvalidOperationException("Unable to load image stream data.");
                    }

                    if (imageSource.CachingEnabled)
                    {
                        CacheImage(imageData, pathToImageCache);
                    }
                }

                var image = UIImage.LoadFromData(imageData, scale);

                if (image == null)
                {
                    throw new InvalidOperationException($"Unable to decode image from URI '{imageSource.Uri}'.");
                }

                var result = new ImageSourceServiceResult(image, () => image.Dispose());

                return(result);
            }
            catch (Exception ex)
            {
                Logger?.LogWarning(ex, "Unable to load image URI '{Uri}'.", imageSource.Uri);
                throw;
            }
        }
 protected override object LoadImage(Stream stream)
 {
     return(UIImage.LoadFromData(NSData.FromStream(stream), 2));
 }
        static Exception createExceptionForNSError(NSError error)
        {
            var innerException = new NSErrorException(error);

            // errors that exists in both share the same error code, so we can use a single switch/case
            // this also ease watchOS integration as if does not expose CFNetwork but (I would not be
            // surprised if it)could return some of it's error codes
#if __WATCHOS__
            if (error.Domain == NSError.NSUrlErrorDomain)
            {
#else
            if ((error.Domain == NSError.NSUrlErrorDomain) || (error.Domain == NSError.CFNetworkErrorDomain))
            {
#endif
                // Apple docs: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/index.html#//apple_ref/doc/constant_group/URL_Loading_System_Error_Codes
                // .NET docs: http://msdn.microsoft.com/en-us/library/system.net.webexceptionstatus(v=vs.110).aspx
                switch ((NSUrlError)(long)error.Code)
                {
                case NSUrlError.Cancelled:
                case NSUrlError.UserCancelledAuthentication:
#if !__WATCHOS__
                case (NSUrlError)NSNetServicesStatus.CancelledError:
#endif
                    // No more processing is required so just return.
                    return(new OperationCanceledException(error.LocalizedDescription, innerException));
                }
            }

            return(new HttpRequestException(error.LocalizedDescription, innerException));
        }

        string GetHeaderSeparator(string name)
        {
            string value;

            if (!headerSeparators.TryGetValue(name, out value))
            {
                value = ",";
            }
            return(value);
        }

        async Task <NSUrlRequest> CreateRequest(HttpRequestMessage request)
        {
            var stream  = Stream.Null;
            var headers = request.Headers as IEnumerable <KeyValuePair <string, IEnumerable <string> > >;

            if (request.Content != null)
            {
                stream = await request.Content.ReadAsStreamAsync().ConfigureAwait(false);

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

            var nsrequest = new NSMutableUrlRequest {
                AllowsCellularAccess = allowsCellularAccess,
                CachePolicy          = DisableCaching ? NSUrlRequestCachePolicy.ReloadIgnoringCacheData : NSUrlRequestCachePolicy.UseProtocolCachePolicy,
                HttpMethod           = request.Method.ToString().ToUpperInvariant(),
                Url     = NSUrl.FromString(request.RequestUri.AbsoluteUri),
                Headers = headers.Aggregate(new NSMutableDictionary(), (acc, x) => {
                    acc.Add(new NSString(x.Key), new NSString(string.Join(GetHeaderSeparator(x.Key), x.Value)));
                    return(acc);
                })
            };

            if (stream != Stream.Null)
            {
                // HttpContent.TryComputeLength is `protected internal` :-( but it's indirectly called by headers
                var length = request.Content.Headers.ContentLength;
                if (length.HasValue && (length <= MaxInputInMemory))
                {
                    nsrequest.Body = NSData.FromStream(stream);
                }
                else
                {
                    nsrequest.BodyStream = new WrappedNSInputStream(stream);
                }
            }
            return(nsrequest);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            this.View.Add(this.tableView);
            this.View.Add(this.mapView);
            this.tableView.Source              = this.momentsTableViewSource;
            this.mapView.GetViewForAnnotation += (mapView, annotation) => {
                if (annotation is MKUserLocation)
                {
                    return(null);
                }

                // create pin annotation view
                MKAnnotationView pinView = (MKPinAnnotationView)mapView.DequeueReusableAnnotation("MomentPin");

                if (pinView == null)
                {
                    pinView = new MKPinAnnotationView(annotation, "MomentPin");
                }
                if (annotation is MomentAnnotation)
                {
                    Moment moment = ((MomentAnnotation)annotation).Moment;
                    var    button = UIButton.FromType(UIButtonType.DetailDisclosure);
                    button.TouchDown += (sender, e) => {
                        EditDialog dialog = new EditDialog();
                        dialog.Config(moment);
                        this.NavigationController.PushViewController(dialog, true);
                    };
                    pinView.RightCalloutAccessoryView = button;

                    if (moment.Media.Count > 0)
                    {
                        NSData data = null;
                        if (moment.Media[0].URL != null)
                        {
                            if (moment.Media[0].Type == "Image")
                            {
                                using (Stream imageStream = AppDelegate.MomentsManager.FileSystem.getFileStream(moment.Media[0].URL)) {
                                    data = NSData.FromStream(imageStream);
                                    AppDelegate.MomentsManager.FileSystem.CloseFileStream(imageStream);
                                }

                                pinView.LeftCalloutAccessoryView = new UIImageView()
                                {
                                    Bounds = new CGRect(0, 0, 40, 40),
                                    Image  = UIImage.LoadFromData(data)
                                };
                            }
                            else
                            {
                                var     nsurl = NSUrl.FromFilename((Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/" + moment.Media [0].URL));
                                AVAsset asset = AVAsset.FromUrl(nsurl);
                                AVAssetImageGenerator generator = new AVAssetImageGenerator(asset);
                                generator.AppliesPreferredTrackTransform = true;
                                NSError err           = null;
                                CMTime  outTime       = new CMTime();
                                CMTime  requestedTime = new CMTime(2, 1);                                  // To create thumbnail image
                                using (var imgRef = generator.CopyCGImageAtTime(requestedTime, out outTime, out err)){
                                    pinView.LeftCalloutAccessoryView = new UIImageView()
                                    {
                                        Bounds = new CGRect(0, 0, 40, 40),
                                        Image  = UIImage.FromImage(imgRef)
                                    };
                                }
                            }
                            pinView.LeftCalloutAccessoryView.Layer.CornerRadius  = 20;
                            pinView.LeftCalloutAccessoryView.Layer.MasksToBounds = true;
                        }
                    }
                    else
                    {
                        pinView.LeftCalloutAccessoryView = null;
                    }
                    if (moment.State == MomentState.Finished)
                    {
                        ((MKPinAnnotationView)pinView).PinColor = MKPinAnnotationColor.Green;
                    }
                    else if (moment.State == MomentState.InProgress)
                    {
                        ((MKPinAnnotationView)pinView).PinColor = MKPinAnnotationColor.Purple;
                    }
                    else
                    {
                        ((MKPinAnnotationView)pinView).PinColor = MKPinAnnotationColor.Red;
                    }
                    pinView.CanShowCallout = true;
                }

                return(pinView);
            };

            //this.TabBarItem = new UITabBarItem ("My Moments", UIImage.FromFile ("images/moments.png"), 1);
            this.tableView.SeparatorInset      = new UIEdgeInsets(0, 0, 0, 0);
            this.tableView.TintColor           = this.NavigationController.NavigationBar.TintColor;
            AppDelegate.MomentsManager.Synced += () => {
                this.tableView.ReloadData();
                updateMap();
            };
        }
Beispiel #14
0
 public static NSImage FromStream(System.IO.Stream stream)
 {
     using (NSData data = NSData.FromStream(stream)) {
         return(new NSImage(data));
     }
 }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            TakePhoto.Enabled = CrossMedia.Current.IsTakePhotoSupported;
            PickPhoto.Enabled = CrossMedia.Current.IsPickPhotoSupported;

            TakeVideo.Enabled = CrossMedia.Current.IsTakeVideoSupported;
            PickVideo.Enabled = CrossMedia.Current.IsPickVideoSupported;

            TakePhoto.TouchUpInside += async(sender, args) =>
            {
                var cts = new CancellationTokenSource();
                if (SwitchCancel.On)
                {
                    cts.CancelAfter(TimeSpan.FromSeconds(10));
                }
                Func <object> func = CreateOverlay;
                var           test = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
                {
                    Name                = "test1.jpg",
                    SaveToAlbum         = AlbumSwitch.On,
                    PhotoSize           = SizeSwitch.On ? PhotoSize.Medium : PhotoSize.Full,
                    OverlayViewProvider = OverlaySwitch.On ? func : null,
                    AllowCropping       = CroppingSwitch.On,
                    CompressionQuality  = (int)SliderQuality.Value,
                    Directory           = "Sample",
                    DefaultCamera       = FrontSwitch.On ? CameraDevice.Front : CameraDevice.Rear,
                    RotateImage         = SwitchRotate.On
                }, cts.Token);

                if (test == null)
                {
                    return;
                }

                var stream = test.GetStream();

                //NSData* pngdata = UIImagePNGRepresentation(self.workingImage); //PNG wrap
                // UIImage* img = [self rotateImageAppropriately:[UIImage imageWithData: pngdata]];
                // UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil);

                using (var data = NSData.FromStream(stream))
                {
                    MainImage.Image = UIImage.LoadFromData(data);
                }

                test.Dispose();
            };

            PickPhoto.TouchUpInside += async(sender, args) =>
            {
                var cts = new CancellationTokenSource();
                if (SwitchCancel.On)
                {
                    cts.CancelAfter(TimeSpan.FromSeconds(10));
                }
                var test = await CrossMedia.Current.PickPhotoAsync(
                    new PickMediaOptions
                {
                    PhotoSize          = SizeSwitch.On ? PhotoSize.Medium : PhotoSize.Full,
                    CompressionQuality = (int)SliderQuality.Value,
                    RotateImage        = SwitchRotate.On
                }, cts.Token);

                cts.Dispose();
                if (test == null)
                {
                    return;
                }

                new UIAlertView("Success", test.Path, null, "OK").Show();

                var stream = test.GetStream();
                using (var data = NSData.FromStream(stream))
                    MainImage.Image = UIImage.LoadFromData(data);

                test.Dispose();
            };

            TakeVideo.TouchUpInside += async(sender, args) =>
            {
                var cts = new CancellationTokenSource();
                if (SwitchCancel.On)
                {
                    cts.CancelAfter(TimeSpan.FromSeconds(10));
                }
                var test = await CrossMedia.Current.TakeVideoAsync(new Plugin.Media.Abstractions.StoreVideoOptions
                {
                    Name        = "test1.mp4",
                    SaveToAlbum = true
                }, cts.Token);

                if (test == null)
                {
                    return;
                }

                new UIAlertView("Success", test.Path, null, "OK").Show();

                test.Dispose();
            };

            PickVideo.TouchUpInside += async(sender, args) =>
            {
                var cts = new CancellationTokenSource();
                if (SwitchCancel.On)
                {
                    cts.CancelAfter(TimeSpan.FromSeconds(10));
                }
                var test = await CrossMedia.Current.PickVideoAsync(cts.Token);

                if (test == null)
                {
                    return;
                }

                new UIAlertView("Success", test.Path, null, "OK").Show();

                test.Dispose();
            };
            // Perform any additional setup after loading the view, typically from a nib.
        }
Beispiel #16
0
 public override object LoadFromStream(Stream stream)
 {
     using (NSData data = NSData.FromStream(stream)) {
         return(new NSImage(data));
     }
 }
Beispiel #17
0
		public static Texture2D FromStream(GraphicsDevice graphicsDevice, Stream stream)
		{
            //todo: partial classes would be cleaner
#if IOS || MONOMAC
            


#if IOS
			using (var uiImage = UIImage.LoadFromData(NSData.FromStream(stream)))
#elif MONOMAC
			using (var nsImage = NSImage.FromStream (stream))
#endif
			{
#if IOS
				var cgImage = uiImage.CGImage;
#elif MONOMAC
				var rectangle = RectangleF.Empty;
				var cgImage = nsImage.AsCGImage (ref rectangle, null, null);
#endif
				
				var width = cgImage.Width;
				var height = cgImage.Height;
				
				var data = new byte[width * height * 4];
				
				var colorSpace = CGColorSpace.CreateDeviceRGB();
				var bitmapContext = new CGBitmapContext(data, width, height, 8, width * 4, colorSpace, CGBitmapFlags.PremultipliedLast);
				bitmapContext.DrawImage(new RectangleF(0, 0, width, height), cgImage);
				bitmapContext.Dispose();
				colorSpace.Dispose();
				
                Texture2D texture = null;
                Threading.BlockOnUIThread(() =>
                {
				    texture = new Texture2D(graphicsDevice, width, height, false, SurfaceFormat.Color);			
    				texture.SetData(data);
                });
			
				return texture;
			}
#elif ANDROID
            using (Bitmap image = BitmapFactory.DecodeStream(stream, null, new BitmapFactory.Options
            {
                InScaled = false,
                InDither = false,
                InJustDecodeBounds = false,
                InPurgeable = true,
                InInputShareable = true,
            }))
            {
                var width = image.Width;
                var height = image.Height;

                int[] pixels = new int[width * height];
                if ((width != image.Width) || (height != image.Height))
                {
                    using (Bitmap imagePadded = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888))
                    {
                        Canvas canvas = new Canvas(imagePadded);
                        canvas.DrawARGB(0, 0, 0, 0);
                        canvas.DrawBitmap(image, 0, 0, null);
                        imagePadded.GetPixels(pixels, 0, width, 0, 0, width, height);
                        imagePadded.Recycle();
                    }
                }
                else
                {
                    image.GetPixels(pixels, 0, width, 0, 0, width, height);
                }
                image.Recycle();

                // Convert from ARGB to ABGR
                for (int i = 0; i < width * height; ++i)
                {
                    uint pixel = (uint)pixels[i];
                    pixels[i] = (int)((pixel & 0xFF00FF00) | ((pixel & 0x00FF0000) >> 16) | ((pixel & 0x000000FF) << 16));
                }

                Texture2D texture = null;
                Threading.BlockOnUIThread(() =>
                {
                    texture = new Texture2D(graphicsDevice, width, height, false, SurfaceFormat.Color);
                    texture.SetData<int>(pixels);
                });

                return texture;
            }
#elif WINDOWS_PHONE
            throw new NotImplementedException();

#elif WINDOWS_STOREAPP || DIRECTX

            // For reference this implementation was ultimately found through this post:
            // http://stackoverflow.com/questions/9602102/loading-textures-with-sharpdx-in-metro 
            Texture2D toReturn = null;
			SharpDX.WIC.BitmapDecoder decoder;
			
            using(var bitmap = LoadBitmap(stream, out decoder))
			using (decoder)
			{
				SharpDX.Direct3D11.Texture2D sharpDxTexture = CreateTex2DFromBitmap(bitmap, graphicsDevice);

				toReturn = new Texture2D(graphicsDevice, bitmap.Size.Width, bitmap.Size.Height);

				toReturn._texture = sharpDxTexture;
			}
            return toReturn;
#elif PSM
            return new Texture2D(graphicsDevice, stream);
#else
            using (Bitmap image = (Bitmap)Bitmap.FromStream(stream))
            {
                // Fix up the Image to match the expected format
                image.RGBToBGR();

                var data = new byte[image.Width * image.Height * 4];

                BitmapData bitmapData = image.LockBits(new System.Drawing.Rectangle(0, 0, image.Width, image.Height),
                    ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                if (bitmapData.Stride != image.Width * 4) 
                    throw new NotImplementedException();
                Marshal.Copy(bitmapData.Scan0, data, 0, data.Length);
                image.UnlockBits(bitmapData);

                Texture2D texture = null;
                texture = new Texture2D(graphicsDevice, image.Width, image.Height);
                texture.SetData(data);

                return texture;
            }
#endif
        }
Beispiel #18
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            TakePhoto.Enabled = CrossMedia.Current.IsTakePhotoSupported;
            PickPhoto.Enabled = CrossMedia.Current.IsPickPhotoSupported;

            TakeVideo.Enabled = CrossMedia.Current.IsTakeVideoSupported;
            PickVideo.Enabled = CrossMedia.Current.IsPickVideoSupported;

            TakePhoto.TouchUpInside += async(sender, args) =>
            {
                Func <object> func = CreateOverlay;
                var           test = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
                {
                    Name                = "test1.jpg",
                    SaveToAlbum         = AlbumSwitch.On,
                    PhotoSize           = SizeSwitch.On ? Plugin.Media.Abstractions.PhotoSize.Medium : Plugin.Media.Abstractions.PhotoSize.Full,
                    OverlayViewProvider = OverlaySwitch.On ? func : null,
                    AllowCropping       = CroppingSwitch.On,
                    CompressionQuality  = (int)SliderQuality.Value,
                    Directory           = "Sample",
                    DefaultCamera       = FrontSwitch.On ? Plugin.Media.Abstractions.CameraDevice.Front : Plugin.Media.Abstractions.CameraDevice.Rear
                });

                if (test == null)
                {
                    return;
                }

                new UIAlertView("Success", test.Path, null, "OK").Show();

                var stream = test.GetStream();
                using (var data = NSData.FromStream(stream))
                    MainImage.Image = UIImage.LoadFromData(data);

                test.Dispose();
            };

            PickPhoto.TouchUpInside += async(sender, args) =>
            {
                var test = await CrossMedia.Current.PickPhotoAsync(
                    new Plugin.Media.Abstractions.PickMediaOptions
                {
                    PhotoSize          = SizeSwitch.On ? Plugin.Media.Abstractions.PhotoSize.Medium : Plugin.Media.Abstractions.PhotoSize.Full,
                    CompressionQuality = (int)SliderQuality.Value
                });

                if (test == null)
                {
                    return;
                }

                new UIAlertView("Success", test.Path, null, "OK").Show();

                var stream = test.GetStream();
                using (var data = NSData.FromStream(stream))
                    MainImage.Image = UIImage.LoadFromData(data);

                test.Dispose();
            };

            TakeVideo.TouchUpInside += async(sender, args) =>
            {
                var test = await CrossMedia.Current.TakeVideoAsync(new Plugin.Media.Abstractions.StoreVideoOptions
                {
                    Name        = "test1.mp4",
                    SaveToAlbum = true
                });

                if (test == null)
                {
                    return;
                }

                new UIAlertView("Success", test.Path, null, "OK").Show();

                test.Dispose();
            };

            PickVideo.TouchUpInside += async(sender, args) =>
            {
                var test = await CrossMedia.Current.PickVideoAsync();

                if (test == null)
                {
                    return;
                }

                new UIAlertView("Success", test.Path, null, "OK").Show();

                test.Dispose();
            };
            // Perform any additional setup after loading the view, typically from a nib.
        }
Beispiel #19
0
        private static Texture2D PlatformFromStream(GraphicsDevice graphicsDevice, Stream stream)
        {
#if IOS || MONOMAC
#if IOS
            using (var uiImage = UIImage.LoadFromData(NSData.FromStream(stream)))
#elif MONOMAC
            using (var nsImage = NSImage.FromStream(stream))
#endif
            {
#if IOS
                var cgImage = uiImage.CGImage;
#elif MONOMAC
#if PLATFORM_MACOS_LEGACY
                var rectangle = RectangleF.Empty;
#else
                var rectangle = CGRect.Empty;
#endif
                var cgImage = nsImage.AsCGImage(ref rectangle, null, null);
#endif

                return(PlatformFromStream(graphicsDevice, cgImage));
            }
#endif
#if ANDROID
            using (Bitmap image = BitmapFactory.DecodeStream(stream, null, new BitmapFactory.Options
            {
                InScaled = false,
                InDither = false,
                InJustDecodeBounds = false,
                InPurgeable = true,
                InInputShareable = true,
            }))
            {
                return(PlatformFromStream(graphicsDevice, image));
            }
#endif
#if DESKTOPGL || ANGLE
            Bitmap image = (Bitmap)Bitmap.FromStream(stream);
            try
            {
                // Fix up the Image to match the expected format
                image = (Bitmap)image.RGBToBGR();

                var data = new byte[image.Width * image.Height * 4];

                BitmapData bitmapData = image.LockBits(new System.Drawing.Rectangle(0, 0, image.Width, image.Height),
                                                       ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                if (bitmapData.Stride != image.Width * 4)
                {
                    throw new NotImplementedException();
                }
                Marshal.Copy(bitmapData.Scan0, data, 0, data.Length);
                image.UnlockBits(bitmapData);

                Texture2D texture = null;
                texture = new Texture2D(graphicsDevice, image.Width, image.Height);
                texture.SetData(data);

                return(texture);
            }
            finally
            {
                image.Dispose();
            }
#endif
        }
Beispiel #20
0
        public void Create(Stream stream)
        {
            var data = NSData.FromStream(stream);

            Control = new NSImage(data);
        }
Beispiel #21
0
 internal static Bitmap Create(Stream stream)
 {
     return((Bitmap)UIImage.LoadFromData(NSData.FromStream(stream)).CGImage);
 }