예제 #1
0
        public void FromDataTest()
        {
#if MONOMAC
            NSData data = NSData.FromFile(NSBundle.MainBundle.PathForResource("xamarin2", "png"));
#else
            NSData data = NSData.FromFile(filename);
#endif

            using (var img = CGImageSource.FromData(data)) {
                Assert.NotNull(img, "#a1");
            }

            using (var img = CGImageSource.FromData(data, new CGImageOptions())) {
                Assert.NotNull(img, "#b1");
            }

            using (var img = CGImageSource.FromData(data, null)) {
                Assert.NotNull(img, "#c1");
            }
        }
예제 #2
0
        static public async Task <FormsCAKeyFrameAnimation> CreateAnimationFromUriImageSourceAsync(UriImageSource imageSource, CancellationToken cancelationToken = default(CancellationToken))
        {
            FormsCAKeyFrameAnimation animation = null;

            if (imageSource is IStreamImageSource streamImageSource)
            {
                using (var streamImage = await streamImageSource.GetStreamAsync(cancelationToken).ConfigureAwait(false))
                {
                    if (streamImage != null)
                    {
                        using (var parsedImageSource = CGImageSource.FromData(NSData.FromStream(streamImage)))
                        {
                            animation = ImageAnimationHelper.CreateAnimationFromCGImageSource(parsedImageSource);
                        }
                    }
                }
            }

            return(animation);
        }
예제 #3
0
        public static UIImage LoadGIFImage(string gifImage)
        {
            try
            {
                using (NSData imgData = NSData.FromFile(gifImage))
                    using (CGImageSource imgSource = CGImageSource.FromData(imgData))
                    {
                        NSString      gifKey      = new NSString(GIFKey);
                        NSString      gifDelayKey = new NSString(GIFDelayTimeKey);
                        List <double> frameDelays = new List <double>();

                        // Array that will hold each GIF frame.
                        UIImage[] frames = new UIImage[imgSource.ImageCount];

                        // Get all individual frames and their delay time.
                        for (int i = 0; i < imgSource.ImageCount; i++)
                        {
                            // Get the frame's property dictionary and the '{GIF}' dictionary from that.
                            using (NSDictionary frameProps = imgSource.CopyProperties(null, i))
                                using (NSMutableDictionary gifDict = (NSMutableDictionary)frameProps[gifKey])
                                {
                                    double frameDelay = ((NSNumber)gifDict[gifDelayKey]).DoubleValue;
                                    frameDelays.Add(frameDelay);
                                }                //end using

                            // Fill the array.
                            using (CGImage cgImage = imgSource.CreateImage(i, null))
                            {
                                frames[i] = UIImage.FromImage(cgImage);
                            }            //end using cgImage
                        }                //end for

                        // Create animated image.
                        return(UIImage.CreateAnimatedImage(frames, frameDelays.Sum()));
                    }            //end using
            } catch (Exception ex)
            {
                // Something went wrong!
                throw ex;
            }    //end try catch
        }        //end static UIImage LoadGifImage
        public void CopyImageSource()
        {
            if (!TestRuntime.CheckSystemAndSDKVersion(7, 0))
            {
                Assert.Ignore("Requires iOS 7+");
            }

            using (NSData data = NSData.FromFile("xamarin2.png"))
                using (var source = CGImageSource.FromData(data))
                    using (NSMutableData destData = new NSMutableData())
#if XAMCORE_2_0 // FromData => Create
                        using (var id = CGImageDestination.Create(destData, GoodUti, 1)) {
#else
                        using (var id = CGImageDestination.FromData(destData, GoodUti, 1)) {
#endif
                            NSError err;
                            // testing that null is allowed (no crash) so the fact that is return false and an error does not matter
                            Assert.False(id.CopyImageSource(source, (NSDictionary)null, out err), "CopyImageSource");
                            Assert.NotNull(err, "NSError");
                        }
        }
예제 #5
0
        private async Task LoadImage()
        {
            NSData bytes = null;
            var    s     = img.Img;

            bytes = await Task.Run(() => { return(NSData.FromFile(s + ".gif")); });

            if (bytes == null)
            {
                return;
            }
            try
            {
                var sourceRef = CGImageSource.FromData(bytes);
                CreateAnimatedImageView(sourceRef, Control);
            }
            catch (Exception ex)
            {
                //Debug.WriteLine("Unable to load gif: " + ex.Message);
            }
        }
예제 #6
0
        public void CopyImageSource()
        {
            TestRuntime.AssertXcodeVersion(5, 0);

#if MONOMAC
            using (NSData data = NSData.FromFile(NSBundle.MainBundle.PathForResource("xamarin2", "png")))
#else
            using (NSData data = NSData.FromFile("xamarin2.png"))
#endif
                using (var source = CGImageSource.FromData(data))
                    using (NSMutableData destData = new NSMutableData())
#if XAMCORE_2_0 // FromData => Create
                        using (var id = CGImageDestination.Create(destData, GoodUti, 1)) {
#else
                        using (var id = CGImageDestination.FromData(destData, GoodUti, 1)) {
#endif
                            NSError err;
                            // testing that null is allowed (no crash) so the fact that is return false and an error does not matter
                            Assert.False(id.CopyImageSource(source, (NSDictionary)null, out err), "CopyImageSource");
                            Assert.NotNull(err, "NSError");
                        }
        }
예제 #7
0
        public void AvailableDepthDataTypesTest()
        {
#if !MONOMAC
            TestRuntime.AssertDevice();
#endif
            TestRuntime.AssertXcodeVersion(9, 0);

            // xamarinmonkey.heic is the new photo format, also this one includes depth data
            var imgdata = NSData.FromUrl(NSBundle.MainBundle.GetUrlForResource("xamarinmonkey", "heic", "CoreImage"));
            Assert.NotNull(imgdata, "imgdata");

            var imageSource = CGImageSource.FromData(imgdata);
            Assert.NotNull(imageSource, "imageSource");

            var info = imageSource.CopyAuxiliaryDataInfo(0, CGImageAuxiliaryDataType.Disparity);
            Assert.NotNull(info, "info");

            NSError err;
            var     depthData = AVDepthData.Create(info, out err);
            Assert.NotNull(depthData, "depthData");
            Assert.NotNull(depthData.AvailableDepthDataTypes, "AvailableDepthDataTypes");
        }
        private void FinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs e)
        {
            var originalImage = e.Info[UIImagePickerController.OriginalImage] as UIImage;

            if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
            {
                var imageManager = new PHImageManager();
                imageManager.RequestImageData(e.PHAsset, null, (data, dataUti, orientation, info) =>
                {
                    var source   = CGImageSource.FromData(data);
                    var metadata = source.GetProperties(0).Dictionary;

                    GoToDescription(originalImage, UIDeviceOrientation.Portrait, metadata);
                    _imagePicker.DismissViewControllerAsync(false);
                });
            }
            else
            {
                GoToDescription(originalImage, UIDeviceOrientation.Portrait);
                _imagePicker.DismissViewControllerAsync(false);
            }
        }
예제 #9
0
        protected override async void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            if (e.PropertyName == Image.SourceProperty.PropertyName)
            {
                NSData bytes = null;

                var s = Element.Source;
                if (s is UriImageSource)
                {
                    using (var client = new HttpClient())
                        bytes = NSData.FromArray(await client.GetByteArrayAsync(((UriImageSource)s).Uri));
                }
                else if (s is StreamImageSource)
                {
                    bytes = NSData.FromStream(await((StreamImageSource)s).Stream(default(CancellationToken)));
                }
                else if (s is FileImageSource)
                {
                    bytes = await Task.Run(() => { return(NSData.FromFile(((FileImageSource)s).File)); });
                }

                if (bytes == null)
                {
                    return;
                }

                try
                {
                    var sourceRef = CGImageSource.FromData(bytes);
                    CreateAnimatedImageView(sourceRef, Control);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Unable to load gif: " + ex.Message);
                }
            }
        }
예제 #10
0
        public void AvailableDepthDataTypesTest()
        {
            TestRuntime.AssertDevice();
            TestRuntime.AssertXcodeVersion(9, 0);

            // xamarinmonkey.heic is the new photo format, also this one includes depth data
            var imgdata = NSData.FromFile("CoreImage/xamarinmonkey.heic");

            Assert.NotNull(imgdata, "imgdata");

            var imageSource = CGImageSource.FromData(imgdata);

            Assert.NotNull(imageSource, "imageSource");

            var info = imageSource.CopyAuxiliaryDataInfo(0, CGImageAuxiliaryDataType.Disparity);

            Assert.NotNull(info, "info");

            NSError err;
            var     depthData = AVDepthData.Create(info, out err);

            Assert.NotNull(depthData, "depthData");
            Assert.NotNull(depthData.AvailableDepthDataTypes, "AvailableDepthDataTypes");
        }
예제 #11
0
        protected override async void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            if (e.PropertyName == ImageGifs.ImgProperty.PropertyName)
            {
                NSData bytes = null;
                var    s     = img.Img;
                bytes = await Task.Run(() => { return(NSData.FromFile(s + ".gif")); });

                if (bytes == null)
                {
                    return;
                }
                try
                {
                    var sourceRef = CGImageSource.FromData(bytes);
                    CreateAnimatedImageView(sourceRef, Control);
                }
                catch (Exception ex)
                {
                    //Debug.WriteLine("Unable to load gif: " + ex.Message);
                }
            }
        }
예제 #12
0
        // Shamelessly copied from React-Native: https://github.com/facebook/react-native/blob/2cbc9127560c5f0f89ae5aa6ff863b1818f1c7c3/Libraries/Image/RCTImageUtils.m
        public static UIImage ToImage(this NSData data, CGSize destSize, nfloat destScale, RCTResizeMode resizeMode = RCTResizeMode.ScaleAspectFit, ImageInformation imageinformation = null, bool allowUpscale = false)
        {
            using (var sourceRef = CGImageSource.FromData(data))
            {
                var imageProperties = GetImageProperties(sourceRef);

                if (imageProperties == null)
                {
                    throw new BadImageFormatException("Image is null");
                }

                if (imageinformation != null)
                {
                    if (imageProperties.PixelWidth.HasValue && imageProperties.PixelHeight.HasValue)
                    {
                        imageinformation.SetOriginalSize(imageProperties.PixelWidth.Value, imageProperties.PixelHeight.Value);
                    }
                }

                var sourceSize = new CGSize((nfloat)imageProperties.PixelWidth, (nfloat)imageProperties.PixelHeight);

                if (destSize.IsEmpty)
                {
                    destSize = sourceSize;
                    if (destScale <= 0)
                    {
                        destScale = 1;
                    }
                }
                else if (destScale <= 0)
                {
                    destScale = ScaleHelper.Scale;
                }

                // Calculate target size
                CGSize targetSize      = RCTTargetSize(sourceSize, 1, destSize, destScale, resizeMode, allowUpscale);
                CGSize targetPixelSize = RCTSizeInPixels(targetSize, destScale);
                int    maxPixelSize    = (int)Math.Max(
                    Math.Min(sourceSize.Width, targetPixelSize.Width),
                    Math.Min(sourceSize.Height, targetPixelSize.Height)
                    );

                var options = new CGImageThumbnailOptions()
                {
                    ShouldAllowFloat               = true,
                    CreateThumbnailWithTransform   = true,
                    CreateThumbnailFromImageAlways = true,
                    MaxPixelSize = maxPixelSize,
                    ShouldCache  = false,
                };

                UIImage image = null;

                // gif
                if (sourceRef.ImageCount > 1)
                {
                    image = GifHelper.AnimateGif(sourceRef, destScale);
                }
                else
                {
                    // Get thumbnail
                    using (var imageRef = sourceRef.CreateThumbnail(0, options))
                    {
                        if (imageRef != null)
                        {
                            // Return image
                            image = new UIImage(imageRef, destScale, UIImageOrientation.Up);
                        }
                    }
                }

                if (imageinformation != null && image != null)
                {
                    int width  = (int)image.Size.Width;
                    int height = (int)image.Size.Height;
                    imageinformation.SetCurrentSize(width.PointsToPixels(), height.PointsToPixels());
                }

                return(image);
            }
        }
예제 #13
0
        public static async Task <IDecodedImage <PImage> > SourceRegfToDecodedImageAsync(NSData nsdata, CGSize destSize, nfloat destScale, Configuration config, TaskParameter parameters, RCTResizeMode resizeMode = RCTResizeMode.ScaleAspectFit, ImageInformation imageinformation = null, bool allowUpscale = false)
        {
            using (var sourceRef = CGImageSource.FromData(nsdata))
            {
                if (sourceRef == null)
                {
                    throw new BadImageFormatException("Decoded image is null or corrupted");
                }

                var imageProperties = sourceRef.GetProperties(0);

                if (imageProperties == null || !imageProperties.PixelWidth.HasValue || !imageProperties.PixelHeight.HasValue)
                {
                    throw new BadImageFormatException("Can't read image size properties. File corrupted?");
                }

                imageinformation.SetOriginalSize(imageProperties.PixelWidth.Value, imageProperties.PixelHeight.Value);

                var sourceSize = new CGSize(imageProperties.PixelWidth.Value, imageProperties.PixelHeight.Value);

                if (destSize.IsEmpty)
                {
                    destSize = sourceSize;
                    if (destScale <= 0)
                    {
                        destScale = 1;
                    }
                }
                else if (destScale <= 0)
                {
                    destScale = ScaleHelper.Scale;
                }

                // Calculate target size
                var targetSize      = RCTTargetSize(sourceSize, 1, destSize, destScale, resizeMode, allowUpscale);
                var targetPixelSize = RCTSizeInPixels(targetSize, destScale);
                var maxPixelSize    = (int)Math.Max(
                    allowUpscale ? targetPixelSize.Width : Math.Min(sourceSize.Width, targetPixelSize.Width),
                    allowUpscale ? targetPixelSize.Height : Math.Min(sourceSize.Height, targetPixelSize.Height)
                    );

                var options = new CGImageThumbnailOptions()
                {
                    ShouldAllowFloat               = true,
                    CreateThumbnailWithTransform   = true,
                    CreateThumbnailFromImageAlways = true,
                    MaxPixelSize = maxPixelSize,
                    ShouldCache  = false,
                };

                PImage image = null;
                IAnimatedImage <PImage>[] images = null;

                // GIF
                if (sourceRef.ImageCount > 1 && config.AnimateGifs && imageinformation.Type != ImageInformation.ImageType.ICO)
                {
                    try
                    {
                        await _gifLock.WaitAsync().ConfigureAwait(false);

                        var frameCount = sourceRef.ImageCount;

                        // no need to animate, fail safe.
                        if (frameCount <= 1)
                        {
                            using (var imageRef = sourceRef.CreateThumbnail(0, options))
                            {
#if __IOS__ || __TVOS__
                                image = new PImage(imageRef, destScale, UIImageOrientation.Up);
#elif __MACOS__
                                image = new PImage(imageRef, CGSize.Empty);
#endif
                            }
                        }

#if __IOS__ || __TVOS__
                        var frames         = GetFrames(sourceRef, options);
                        var delays         = GetDelays(sourceRef);
                        var totalDuration  = delays.Sum();
                        var adjustedFrames = AdjustFramesToSpoofDurations(frames, destScale, delays, totalDuration);
                        var avgDuration    = (double)totalDuration / adjustedFrames.Length;

                        images = new AnimatedImage <PImage> [adjustedFrames.Length];

                        for (int i = 0; i < images.Length; i++)
                        {
                            images[i] = new AnimatedImage <PImage>()
                            {
                                Image = adjustedFrames[i], Delay = (int)avgDuration
                            };
                        }
#elif __MACOS__
                        images = new AnimatedImage <PImage> [frameCount];
                        var delays = GetDelays(sourceRef);

                        for (var i = 0; i < images.Length; i++)
                        {
                            var nsImage = new PImage(sourceRef.CreateThumbnail(i, options), CGSize.Empty);
                            images[i] = new AnimatedImage <PImage>()
                            {
                                Image = nsImage, Delay = delays[i]
                            };
                        }
#endif
                    }
                    finally
                    {
                        _gifLock.Release();
                    }
                }
                else
                {
                    // Get thumbnail
                    using (var imageRef = sourceRef.CreateThumbnail(0, options))
                    {
                        if (imageRef != null)
                        {
#if __IOS__ || __TVOS__
                            image = new PImage(imageRef, destScale, UIImageOrientation.Up);
#elif __MACOS__
                            image = new PImage(imageRef, CGSize.Empty);
#endif
                        }
                    }
                }

                var result = new DecodedImage <PImage>();

                if (images != null && images.Length > 1)
                {
                    result.IsAnimated     = true;
                    result.AnimatedImages = images;

                    if (imageinformation != null)
                    {
                        var width  = (int)images[0].Image.Size.Width;
                        var height = (int)images[0].Image.Size.Height;
                        imageinformation.SetCurrentSize(width.DpToPixels(), height.DpToPixels());
                    }
                }
                else
                {
                    result.Image = image;

                    if (imageinformation != null)
                    {
                        var width  = (int)image.Size.Width;
                        var height = (int)image.Size.Height;
                        imageinformation.SetCurrentSize(width.DpToPixels(), height.DpToPixels());
                    }
                }

                return(result);
            }
        }
예제 #14
0
        public static UIImageView GetAnimatedImageView(NSData nsData, UIImageView imageView = null)
        {
            var sourceRef = CGImageSource.FromData(nsData);

            return(CreateAnimatedImageView(sourceRef, imageView));
        }
예제 #15
0
 public AnimatedImage(NSData data)
     : this(CGImageSource.FromData(data, null))
 {
 }
예제 #16
0
        // Shamelessly copied from React-Native: https://github.com/facebook/react-native/blob/2cbc9127560c5f0f89ae5aa6ff863b1818f1c7c3/Libraries/Image/RCTImageUtils.m
        public static NSImage ToImage(this NSData data, CGSize destSize, nfloat destScale, Configuration config, TaskParameter parameters, RCTResizeMode resizeMode = RCTResizeMode.ScaleAspectFit, ImageInformation imageinformation = null, bool allowUpscale = false)
        {
            using (var sourceRef = CGImageSource.FromData(data))
            {
                if (sourceRef == null)
                {
                    throw new BadImageFormatException("Decoded image is null or corrupted");
                }

                var imageProperties = sourceRef.GetProperties(0);

                if (imageProperties == null || !imageProperties.PixelWidth.HasValue || !imageProperties.PixelHeight.HasValue)
                {
                    throw new BadImageFormatException("Can't read image size properties. File corrupted?");
                }

                imageinformation.SetOriginalSize(imageProperties.PixelWidth.Value, imageProperties.PixelHeight.Value);

                var sourceSize = new CGSize(imageProperties.PixelWidth.Value, imageProperties.PixelHeight.Value);
                if (destSize.IsEmpty)
                {
                    destSize = sourceSize;
                    if (destScale <= 0)
                    {
                        destScale = 1;
                    }
                }
                else if (destScale <= 0)
                {
                    destScale = ScaleHelper.Scale;
                }

                // Calculate target size
                CGSize targetSize      = RCTTargetSize(sourceSize, 1, destSize, destScale, resizeMode, allowUpscale);
                CGSize targetPixelSize = RCTSizeInPixels(targetSize, destScale);
                int    maxPixelSize    = (int)Math.Max(
                    allowUpscale ? targetPixelSize.Width : Math.Min(sourceSize.Width, targetPixelSize.Width),
                    allowUpscale ? targetPixelSize.Height : Math.Min(sourceSize.Height, targetPixelSize.Height)
                    );

                var options = new CGImageThumbnailOptions()
                {
                    ShouldAllowFloat               = true,
                    CreateThumbnailWithTransform   = true,
                    CreateThumbnailFromImageAlways = true,
                    MaxPixelSize = maxPixelSize,
                    ShouldCache  = false,
                };

                NSImage image = null;

                // Get thumbnail
                using (var imageRef = sourceRef.CreateThumbnail(0, options))
                {
                    if (imageRef != null)
                    {
                        // Return image
                        image = new NSImage(imageRef, CGSize.Empty);
                    }
                }


                if (imageinformation != null && image != null)
                {
                    int width  = (int)image.Size.Width;
                    int height = (int)image.Size.Height;
                    imageinformation.SetCurrentSize(width.PointsToPixels(), height.PointsToPixels());
                }

                return(image);
            }
        }