Ejemplo n.º 1
0
        private void Save(CGImageDestination dest)
        {
            if (NativeCGImage == null)
            {
                throw new ObjectDisposedException("cgimage");
            }

            bool lastOK = true;
            int  savedFrame = currentFrame, framesSaved = 0;

            for (int frame = 0; frame < frameCount; frame++)
            {
                if (lastOK = TryAddFrame(dest, frame))
                {
                    ++framesSaved;
                }
            }

            if (currentFrame != savedFrame || !lastOK)
            {
                InitializeImageFrame(savedFrame);
            }

            if (framesSaved == 0)
            {
                throw new ArgumentException("No frame could be saved");
            }

            dest.Close();
        }
Ejemplo n.º 2
0
        public void SaveTo(Stream stream, CompressionFormat compression)
        {
            var data = new NSMutableData();
            CGImageDestination dest = null;

            switch (compression)
            {
            case CompressionFormat.Jpeg:
                dest = CGImageDestination.Create(data, MobileCoreServices.UTType.JPEG, imageCount: 1);
                break;

            case CompressionFormat.Png:
                dest = CGImageDestination.Create(data, MobileCoreServices.UTType.PNG, imageCount: 1);
                break;
            }
            if (dest != null)
            {
                dest.AddImage(cgImage);
                dest.Close();
                using (var bitmapStream = data.AsStream()) {
                    bitmapStream.CopyTo(stream);
                }
                data.Dispose();
            }
        }
Ejemplo n.º 3
0
 public void FromData_BadITU()
 {
     using (NSMutableData destData = new NSMutableData()) {
         Assert.Null(CGImageDestination.Create(destData, BadUti, 1), "FromData-1");
         Assert.Null(CGImageDestination.Create(destData, BadUti, 1, new CGImageDestinationOptions()), "FromData-2");
     }
 }
        public Task <string> CreateThumbnailAsync(string videoPath)
        {
            return(Task.Run(() =>
            {
                var url = NSUrl.FromFilename(videoPath);
                var asset = AVAsset.FromUrl(url);
                var assetImageGenerator = AVAssetImageGenerator.FromAsset(asset);
                assetImageGenerator.AppliesPreferredTrackTransform = true;

                var time = CMTime.FromSeconds(1, 1);

                using (var img = assetImageGenerator.CopyCGImageAtTime(time, out CMTime _, out NSError __))
                {
                    if (img == null)
                    {
                        Debug.WriteLine($"Could not find file at url: {videoPath}");
                        return string.Empty;
                    }

                    var outputPath = Path.ChangeExtension(videoPath, ".png");
                    var fileUrl = NSUrl.FromFilename(outputPath);

                    using (var imageDestination = CGImageDestination.Create(fileUrl, UTType.PNG, 1))
                    {
                        imageDestination.AddImage(img);
                        imageDestination.Close();
                    }

                    return outputPath;
                }
            }));
        }
Ejemplo n.º 5
0
        internal static async Task <StorageItemThumbnail> CreateVideoThumbnailAsync(StorageFile file)
        {
            AVAsset asset = AVUrlAsset.FromUrl(NSUrl.FromFilename(file.Path));
            AVAssetImageGenerator generator = AVAssetImageGenerator.FromAsset(asset);

            generator.AppliesPreferredTrackTransform = true;
            NSError error;
            CMTime  actualTime;
            CMTime  time  = CMTime.FromSeconds(asset.Duration.Seconds / 2, asset.Duration.TimeScale);
            CGImage image = generator.CopyCGImageAtTime(time, out actualTime, out error);

#if __MAC__
            NSMutableData      buffer = new NSMutableData();
            CGImageDestination dest   = CGImageDestination.Create(buffer, UTType.JPEG, 1, null);
            dest.AddImage(image);
            return(new StorageItemThumbnail(buffer.AsStream()));
#else
            UIImage image2 = UIImage.FromImage(image);
            image.Dispose();

            UIImage image3 = image2.Scale(new CGSize(240, 240));
            image2.Dispose();

            return(new StorageItemThumbnail(image3.AsJPEG().AsStream()));
#endif
        }
Ejemplo n.º 6
0
        internal static async Task <StorageItemThumbnail> CreatePhotoThumbnailAsync(StorageFile file)
        {
#if __MAC__
            NSImage image = NSImage.FromStream(await file.OpenStreamForReadAsync());
            double  ratio = image.Size.Width / image.Size.Height;

            NSImage newImage = new NSImage(new CGSize(240, 240 * ratio));
            newImage.LockFocus();
            image.Size = newImage.Size;

            image.Draw(new CGPoint(0, 0), new CGRect(0, 0, newImage.Size.Width, newImage.Size.Height), NSCompositingOperation.Copy, 1.0f);
            newImage.UnlockFocus();

            NSMutableData      buffer = new NSMutableData();
            CGImageDestination dest   = CGImageDestination.Create(buffer, UTType.JPEG, 1);
            dest.AddImage(newImage.CGImage);

            return(new StorageItemThumbnail(buffer.AsStream()));
#else
            UIImage image = UIImage.FromFile(file.Path);

            UIImage image2 = image.Scale(new CGSize(240, 240));
            image.Dispose();

            return(new StorageItemThumbnail(image2.AsJPEG().AsStream()));
#endif
        }
Ejemplo n.º 7
0
 public void Create_DataConsumer_BadUTI()
 {
     using (NSMutableData destData = new NSMutableData())
         using (var consumer = new CGDataConsumer(destData)) {
             Assert.Null(CGImageDestination.Create(consumer, BadUti, 1), "Create-1");
             Assert.Null(CGImageDestination.Create(consumer, BadUti, 1, new CGImageDestinationOptions()), "Create-2");
         }
 }
Ejemplo n.º 8
0
        private static void SaveTempImage(CIImage fullimage, UIImage image, string outputFilename, int quality, bool rotate)
        {
            var imageData       = image.AsJPEG(quality);
            var dataProvider    = new CGDataProvider(imageData);
            var cgImageFromJpeg = CGImage.FromJPEG(dataProvider, null, false, CGColorRenderingIntent.Default);
            var imageWithExif   = new NSMutableData();
            var destination     = CGImageDestination.Create(imageWithExif, UTType.JPEG, 1);
            var cgImageMetadata = new CGMutableImageMetadata();
            var options         = new CGImageDestinationOptions();

            if (fullimage.Properties.DPIWidthF != null)
            {
                options.Dictionary[ImageIO.CGImageProperties.DPIWidth] =
                    new NSNumber((nfloat)fullimage.Properties.DPIWidthF);
            }
            if (fullimage.Properties.DPIWidthF != null)
            {
                options.Dictionary[ImageIO.CGImageProperties.DPIHeight] =
                    new NSNumber((nfloat)fullimage.Properties.DPIHeightF);
            }
            options.ExifDictionary = fullimage.Properties?.Exif ?? new CGImagePropertiesExif();
            options.TiffDictionary = fullimage.Properties?.Tiff ?? new CGImagePropertiesTiff();
            options.GpsDictionary  = fullimage.Properties?.Gps ?? new CGImagePropertiesGps();
            options.JfifDictionary = fullimage.Properties?.Jfif ?? new CGImagePropertiesJfif();
            options.IptcDictionary = fullimage.Properties?.Iptc ?? new CGImagePropertiesIptc();
            if (rotate)
            {
                options.Dictionary[ImageIO.CGImageProperties.Orientation] =
                    new NSString(UIImageOrientation.Up.ToString());
                var tiffDict = new CGImagePropertiesTiff();
                foreach (KeyValuePair <NSObject, NSObject> x in options.TiffDictionary.Dictionary)
                {
                    tiffDict.Dictionary.SetValueForKey(x.Value, x.Key as NSString);
                }
                tiffDict.Dictionary.SetValueForKey(new NSNumber(1), new NSString("Orientation"));
                options.TiffDictionary = tiffDict;
            }
            else
            {
                if (fullimage.Properties.Orientation != null)
                {
                    options.Dictionary[ImageIO.CGImageProperties.Orientation] =
                        new NSString(image.Orientation.ToString());
                }
            }
            destination.AddImageAndMetadata(cgImageFromJpeg, cgImageMetadata, options);
            var success = destination.Close();

            if (success)
            {
                imageWithExif.Save(outputFilename, true);
            }
            else
            {
                imageData.Save(outputFilename, true);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// imageをPNGデータに変換します
        /// </summary>
        private static NSData ConvertImageToPng(CGImage image)
        {
            var storage = new NSMutableData();
            var dest    = CGImageDestination.Create(storage, MobileCoreServices.UTType.PNG, imageCount: 1);

            dest.AddImage(image);
            dest.Close();
            return(storage);
        }
Ejemplo n.º 10
0
 public void FromData_GoodITU()
 {
     using (NSMutableData destData = new NSMutableData()) {
         using (var id = CGImageDestination.Create(destData, GoodUti, 1)) {
             Assert.That(id.Handle, Is.Not.EqualTo(IntPtr.Zero), "handle-1");
         }
         using (var id = CGImageDestination.Create(destData, GoodUti, 1, new CGImageDestinationOptions())) {
             Assert.That(id.Handle, Is.Not.EqualTo(IntPtr.Zero), "handle-2");
         }
     }
 }
Ejemplo n.º 11
0
        private static void Save(CGImage screenshot, string path)
        {
            var fileURL = new NSUrl(path, false);

            using (var dataConsumer = new CGDataConsumer(fileURL))
            {
                var imageDestination = CGImageDestination.Create(dataConsumer, imageFormat, 1);
                imageDestination.AddImage(screenshot);
                imageDestination.Close();
            }
        }
Ejemplo n.º 12
0
        private NSData GetDataWriteMetadata(UIImage originalImage, NSDictionary imageMetadata, float compress)
        {
            //return originalImage.AsJPEG(compress); // turn off efix
            CGImageSource      imgSrc       = CGImageSource.FromData(originalImage.AsJPEG(compress));
            NSMutableData      outImageData = new NSMutableData();
            CGImageDestination dest         = CGImageDestination.Create(outImageData, MobileCoreServices.UTType.JPEG, 1, new CGImageDestinationOptions());

            dest.AddImage(imgSrc, 0, imageMetadata);
            dest.Close();
            return(outImageData);
        }
Ejemplo n.º 13
0
        public void FromUrl_BadITU()
        {
            using (NSUrl url = NSUrl.FromString("file://local")) {
#if XAMCORE_2_0 // FromUrl => Create
                Assert.Null(CGImageDestination.Create(url, BadUti, 1), "FromUrl-1");
#else
                Assert.Null(CGImageDestination.FromUrl(url, BadUti, 1), "FromUrl-1");
                Assert.Null(CGImageDestination.FromUrl(url, BadUti, 1, new CGImageDestinationOptions()), "FromUrl-2");
#endif
            }
        }
Ejemplo n.º 14
0
        public void FromData_BadITU()
        {
            using (NSMutableData destData = new NSMutableData()) {
#if XAMCORE_2_0 // FromData => Create
                Assert.Null(CGImageDestination.Create(destData, BadUti, 1), "FromData-1");
                Assert.Null(CGImageDestination.Create(destData, BadUti, 1, new CGImageDestinationOptions()), "FromData-2");
#else
                Assert.Null(CGImageDestination.FromData(destData, BadUti, 1), "FromData-1");
                Assert.Null(CGImageDestination.FromData(destData, BadUti, 1, new CGImageDestinationOptions()), "FromData-2");
#endif
            }
        }
Ejemplo n.º 15
0
 public void Create_DataConsumer_GoodUTI()
 {
     using (NSMutableData destData = new NSMutableData())
         using (var consumer = new CGDataConsumer(destData)) {
             using (var id = CGImageDestination.Create(consumer, GoodUti, 1)) {
                 Assert.That(id.Handle, Is.Not.EqualTo(IntPtr.Zero), "handle-1");
             }
             using (var id = CGImageDestination.Create(consumer, GoodUti, 1, new CGImageDestinationOptions())) {
                 Assert.That(id.Handle, Is.Not.EqualTo(IntPtr.Zero), "handle-2");
             }
         }
 }
        public void ExportEveryGlyphsAsPNGTo(string path)
        {
            float scale      = Window.BackingScaleFactor;
            var   glyphInfos = _tableViewSource.GlyphInfos;

            //actvw.StartAnimating ();
            Task.Factory.StartNew(() => {
                Func <string, string> makeName = (rawName) => {
                    return(String.Format("{0}_{1}{2}.png", rawName, (int)this.unitFontSize
                                         , ((scale > 2f) ? "@4x" : (scale > 1f) ? "@2x" : "")));
                };
                //string documentDirPath = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
                string documentDirPath = path;

                NSDictionary prop = new NSDictionary();                  //
                int nSucceeded    = 0;
                int nFailed       = 0;
                glyphInfos.ForEach((gi) => {
                    var url = new NSUrl(System.IO.Path.Combine(documentDirPath, makeName(gi.RawName)), false);
                    try {
                        CGImageDestination dest = CGImageDestination.FromUrl(url, "public.png", 1);
                        dest.AddImage(gi.GlyphImage, prop);
                        dest.Close();
                    }
                    catch (Exception ex) {
                        Console.WriteLine(ex.ToString());
                    }
                    if (System.IO.File.Exists(url.Path))
                    {
                        //Console.WriteLine ("Succeeded to write {0}", url);
                        ++nSucceeded;
                    }
                    else
                    {
                        Console.WriteLine("Failed to write {0}", url);
                        ++nFailed;
                    }
                    BeginInvokeOnMainThread(() => {
                        //ShowProgressionLabel (String.Format ("{0} of {1} processed", (nSucceeded + nFailed), glyphInfos.Count));
                    });
                });

                InvokeOnMainThread(() => {
                    //actvw.StopAnimating ();
                    //DismissProgressionLabel ();
                    var alert         = new NSAlert();
                    alert.MessageText = String.Format("{0} succeeded, {1} failed", nSucceeded, nFailed);
                    alert.RunModal();
                });
            });
        }
Ejemplo n.º 17
0
        private void SaveEveryImageToPNG()
        {
            float scale      = UIScreen.MainScreen.Scale;
            var   glyphInfos = _tableViewSource.GlyphInfos;

            actvw.StartAnimating();
            Task.Factory.StartNew(() => {
                Func <string, string> makeName = (rawName) => {
                    return(String.Format("{0}_{1}{2}.png", rawName, (int)this.unitFontSize
                                         , ((scale > 2f) ? "@4x" : (scale > 1f) ? "@2x" : "")));
                };
                string documentDirPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                NSDictionary prop = new NSDictionary();                  //
                int nSucceeded    = 0;
                int nFailed       = 0;
                glyphInfos.ForEach((gi) => {
                    var url = new NSUrl(System.IO.Path.Combine(documentDirPath, makeName(gi.RawName)), false);
                    try {
                        CGImageDestination dest = CGImageDestination.FromUrl(url, "public.png", 1);
                        dest.AddImage(gi.GlyphImage, prop);
                        dest.Close();
                    }
                    catch (Exception ex) {
                        Console.WriteLine(ex.ToString());
                    }
                    if (File.Exists(url.Path))
                    {
                        //Console.WriteLine ("Succeeded to write {0}", url);
                        ++nSucceeded;
                    }
                    else
                    {
                        Console.WriteLine("Failed to write {0}", url);
                        ++nFailed;
                    }
                    BeginInvokeOnMainThread(() => {
                        ShowProgressionLabel(String.Format("{0} of {1} processed", (nSucceeded + nFailed), glyphInfos.Count));
                    });
                });

                InvokeOnMainThread(() => {
                    actvw.StopAnimating();
                    DismissProgressionLabel();
                    var alert = new UIAlertView("Result of save"
                                                , String.Format("{0} succeeded, {1} failed", nSucceeded, nFailed)
                                                , null, "Close", null);
                    alert.Show();
                });
            });
        }
Ejemplo n.º 18
0
        public void CopyImageSource()
        {
            TestRuntime.AssertXcodeVersion(5, 0);

            using (NSData data = NSData.FromFile(NSBundle.MainBundle.PathForResource("xamarin2", "png")))
                using (var source = CGImageSource.FromData(data))
                    using (NSMutableData destData = new NSMutableData())
                        using (var id = CGImageDestination.Create(destData, GoodUti, 1)) {
                            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");
                        }
        }
Ejemplo n.º 19
0
        public new void Save(string path, ImageFormat format)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            // Obtain a URL file path to be passed
            NSUrl url = NSUrl.FromFilename(path);

            // Create an image destination that saves into the path that is passed in
            using (var dest = CGImageDestination.Create(url, GetTypeIdentifier(format), frameCount))
                Save(dest);
        }
        protected override Task <PImage> GenerateImageFromDecoderContainerAsync(IDecodedImage <PImage> decoded, ImageInformation imageInformation, bool isPlaceholder)
        {
            PImage result;

            if (decoded.IsAnimated)
            {
#if __IOS__
                result = PImage.CreateAnimatedImage(decoded.AnimatedImages
                                                    .Select(v => v.Image)
                                                    .Where(v => v?.CGImage != null).ToArray(), decoded.AnimatedImages.Sum(v => v.Delay) / 100.0);
#elif __MACOS__
                using (var mutableData = NSMutableData.Create())
                {
                    var fileOptions = new CGImageDestinationOptions
                    {
                        GifDictionary = new NSMutableDictionary()
                    };
                    fileOptions.GifDictionary[ImageIO.CGImageProperties.GIFLoopCount] = new NSString("0");
                    //options.GifDictionary[ImageIO.CGImageProperties.GIFHasGlobalColorMap] = new NSString("true");

                    using (var destintation = CGImageDestination.Create(mutableData, MobileCoreServices.UTType.GIF, decoded.AnimatedImages.Length, fileOptions))
                    {
                        for (var i = 0; i < decoded.AnimatedImages.Length; i++)
                        {
                            var options = new CGImageDestinationOptions
                            {
                                GifDictionary = new NSMutableDictionary()
                            };
                            options.GifDictionary[ImageIO.CGImageProperties.GIFUnclampedDelayTime] = new NSString(decoded.AnimatedImages[i].Delay.ToString());
                            destintation.AddImage(decoded.AnimatedImages[i].Image.CGImage, options);
                        }

                        destintation.Close();
                    }

                    result = new PImage(mutableData);

                    // TODO I really don't know why representations count is 1, anyone?
                    // var test = result.Representations();
                }
#endif
            }
            else
            {
                result = decoded.Image;
            }

            return(Task.FromResult(result));
        }
Ejemplo n.º 21
0
        public void AddImage()
        {
            string file = Path.Combine(NSBundle.MainBundle.ResourcePath, "basn3p08.png");

            using (NSMutableData destData = new NSMutableData())
#if MONOMAC
                using (var uiimg = new NSImage(NSBundle.MainBundle.PathForResource("basn3p08", "png")))
#else
                using (var uiimg = UIImage.FromFile(file))
#endif
                    using (var img = uiimg.CGImage)
                        using (var id = CGImageDestination.Create(destData, GoodUti, 1)) {
                            id.AddImage(img, (NSDictionary)null);
                        }
        }
Ejemplo n.º 22
0
        public void AddImage()
        {
            string file = Path.Combine(NSBundle.MainBundle.ResourcePath, "basn3p08.png");

            using (NSMutableData destData = new NSMutableData())
                using (var uiimg = UIImage.FromFile(file))
                    using (var img = uiimg.CGImage)
#if XAMCORE_2_0 // FromData => Create
                        using (var id = CGImageDestination.Create(destData, GoodUti, 1)) {
#else
                        using (var id = CGImageDestination.FromData(destData, GoodUti, 1)) {
#endif
                            id.AddImage(img, (NSDictionary)null);
                        }
        }
Ejemplo n.º 23
0
 public void SaveAsPng(string path)
 {
     if (string.IsNullOrEmpty(path))
     {
         throw new ArgumentException("path");
     }
     using (var dest = CGImageDestination.Create(NSUrl.FromFilename(path), "public.png", 1)) {
         if (dest == null)
         {
             throw new InvalidOperationException(string.Format("Could not create image destination {0}.", path));
         }
         dest.AddImage(image);
         dest.Close();
     }
 }
Ejemplo n.º 24
0
        public new void Save(Stream stream, ImageFormat format)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            using (var imageData = new NSMutableData())
            {
                using (var dest = CGImageDestination.Create(imageData, GetTypeIdentifier(format), frameCount))
                    Save(dest);

                using (var ms = imageData.AsStream())
                    ms.CopyTo(stream);
            }
        }
        private async Task <OperationResult <MediaModel> > UploadPhoto(UIImage photo, NSDictionary metadata)
        {
            Stream stream = null;

            try
            {
                var compression    = 1f;
                var maxCompression = 0.1f;
                int maxFileSize    = _photoSize * 1024;

                var byteArray = photo.AsJPEG(compression);

                while (byteArray.Count() > maxFileSize && compression > maxCompression)
                {
                    compression -= 0.1f;
                    byteArray    = photo.AsJPEG(compression);
                }

                if (metadata != null)
                {
                    //exif setup
                    var editedExifData       = RemakeMetadata(metadata, photo);
                    var newImageDataWithExif = new NSMutableData();
                    var imageDestination     = CGImageDestination.Create(newImageDataWithExif, "public.jpeg", 0);
                    imageDestination.AddImage(new UIImage(byteArray).CGImage, editedExifData);
                    imageDestination.Close();
                    stream = newImageDataWithExif.AsStream();
                }
                else
                {
                    stream = byteArray.AsStream();
                }

                var request = new UploadMediaModel(AppSettings.User.UserInfo, stream, ImageExtension);
                return(await _presenter.TryUploadMedia(request));
            }
            catch (Exception ex)
            {
                AppSettings.Reporter.SendCrash(ex);
                return(new OperationResult <MediaModel>(new AppError(LocalizationKeys.PhotoProcessingError)));
            }
            finally
            {
                stream?.Flush();
                stream?.Dispose();
            }
        }
        public void Save(string path)
        {
            var    extension = Path.GetExtension(path).ToLowerInvariant();
            string uttype;

            switch (extension)
            {
            case ".png": uttype = "public.png"; break;

            case ".jpg":
            case ".jpeg": uttype = "public.jpeg"; break;

            default:
                throw new NotSupportedException(string.Format(
                                                    "FramePixelData.Save cannot save images of type: {0}", extension));
            }

            //var documentsDir = Environment.GetFolderPath (Environment.SpecialFolder.Personal);

            var handle = GCHandle.Alloc(_data, GCHandleType.Pinned);

            try {
                var sizeOfColor = Marshal.SizeOf(typeof(Color));
                using (var dataProvider = new CGDataProvider(
                           handle.AddrOfPinnedObject(), _data.Length * sizeOfColor, false))
                    using (var colorSpace = CGColorSpace.CreateDeviceRGB())
                        using (var image = new CGImage(
                                   Width, Height, 8, 32, Width * sizeOfColor, colorSpace,
                                   CGBitmapFlags.ByteOrder32Little | CGBitmapFlags.First,
                                   dataProvider, null, false, CGColorRenderingIntent.Default)) {
                            //var fullPath = Path.Combine (documentsDir, path);
                            Directory.CreateDirectory(Path.GetDirectoryName(path));

                            var url         = NSUrl.FromFilename(Path.GetFullPath(path));
                            var destination = CGImageDestination.FromUrl(url, uttype, 1);
                            destination.AddImage(image, null);
                            if (!destination.Close())
                            {
                                throw new Exception(string.Format(
                                                        "Failed to write the image to '{0}'", path));
                            }
                        }
            } finally {
                handle.Free();
            }
        }
Ejemplo n.º 27
0
        public void AddImageAndMetadata()
        {
            TestRuntime.AssertXcodeVersion(5, 0);

            string file = Path.Combine(NSBundle.MainBundle.ResourcePath, "basn3p08.png");

            using (NSMutableData destData = new NSMutableData())
                using (var uiimg = UIImage.FromFile(file))
                    using (var img = uiimg.CGImage)
#if XAMCORE_2_0 // FromData => Create
                        using (var id = CGImageDestination.Create(destData, GoodUti, 1))
#else
                        using (var id = CGImageDestination.FromData(destData, GoodUti, 1))
#endif
                            using (var mutable = new CGMutableImageMetadata()) {
                                id.AddImageAndMetadata(img, mutable, (NSDictionary)null);
                            }
        }
    public string CreateGif(string frame1Path, string frame2Path, string frame3Path, string frame4Path, string webId, string path = "")
    {
        List <UIImage> listOfFrame = new List <UIImage>();
        UIImage        image1      = new UIImage(frame1Path);

        listOfFrame.Add(image1);
        UIImage image2 = new UIImage(frame2Path);

        listOfFrame.Add(image2);
        UIImage image3 = new UIImage(frame3Path);

        listOfFrame.Add(image3);
        UIImage image4 = new UIImage(frame4Path);

        listOfFrame.Add(image4);
        NSMutableDictionary fileProperties = new NSMutableDictionary
        {
            { CGImageProperties.GIFLoopCount, new NSNumber(1) }
        };
        NSUrl documentsDirectoryUrl = NSFileManager.DefaultManager.GetUrl(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User, null, true, out _);
        NSUrl fileUrl = documentsDirectoryUrl.Append(webId + ".gif", false);

        var destination = CGImageDestination.Create(fileUrl, MobileCoreServices.UTType.GIF, 4);

        destination.SetProperties(fileProperties);
        foreach (var frame in listOfFrame)
        {
            //difference is here, i create a var option and i set the
            //GifDictionary
            var options = new CGImageDestinationOptions();
            options.GifDictionary = new NSMutableDictionary();
            options.GifDictionary[CGImageProperties.GIFDelayTime] = new NSNumber(1f);
            var cgImage = frame.CGImage;
            if (cgImage != null)
            {
                destination.AddImage(cgImage, options);
            }
        }
        if (!destination.Close())
        {
            Console.WriteLine("Failed to finalize the image destination");
        }
        return(fileUrl.Path);
    }
Ejemplo n.º 29
0
        public void SaveAsPng(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException();
            }

            using (var data = new NSMutableData()) {
                using (var dest = CGImageDestination.Create(data, "public.png", 1)) {
                    if (dest == null)
                    {
                        throw new InvalidOperationException(string.Format("Could not create image destination from {0}.", stream));
                    }
                    dest.AddImage(image);
                    dest.Close();
                }
                data.AsStream().CopyTo(stream);
            }
        }
Ejemplo n.º 30
0
        private bool SaveImageWithMetadata(UIImage image, float quality, NSDictionary meta, string path)
        {
            var imageData          = image.AsJPEG(quality);
            var dataProvider       = new CGDataProvider(imageData);
            var cgImageFromJpeg    = CGImage.FromJPEG(dataProvider, null, false, CGColorRenderingIntent.Default);
            var imageWithExif      = new NSMutableData();
            var destination        = CGImageDestination.Create(imageWithExif, UTType.JPEG, 1);
            var cgImageMetadata    = new CGMutableImageMetadata();
            var destinationOptions = new CGImageDestinationOptions();

            if (meta.ContainsKey(ImageIO.CGImageProperties.ExifDictionary))
            {
                destinationOptions.ExifDictionary =
                    new CGImagePropertiesExif(meta[ImageIO.CGImageProperties.ExifDictionary] as NSDictionary);
            }
            if (meta.ContainsKey(ImageIO.CGImageProperties.TIFFDictionary))
            {
                destinationOptions.TiffDictionary = new CGImagePropertiesTiff(meta[ImageIO.CGImageProperties.TIFFDictionary] as NSDictionary);
            }
            if (meta.ContainsKey(ImageIO.CGImageProperties.GPSDictionary))
            {
                destinationOptions.GpsDictionary =
                    new CGImagePropertiesGps(meta[ImageIO.CGImageProperties.GPSDictionary] as NSDictionary);
            }
            if (meta.ContainsKey(ImageIO.CGImageProperties.JFIFDictionary))
            {
                destinationOptions.JfifDictionary =
                    new CGImagePropertiesJfif(meta[ImageIO.CGImageProperties.JFIFDictionary] as NSDictionary);
            }
            if (meta.ContainsKey(ImageIO.CGImageProperties.IPTCDictionary))
            {
                destinationOptions.IptcDictionary =
                    new CGImagePropertiesIptc(meta[ImageIO.CGImageProperties.IPTCDictionary] as NSDictionary);
            }
            destination.AddImageAndMetadata(cgImageFromJpeg, cgImageMetadata, destinationOptions);
            var success = destination.Close();

            if (success)
            {
                imageWithExif.Save(path, true);
            }
            return(success);
        }