Example #1
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
        }
Example #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();
            }
        }
Example #3
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
        }
Example #4
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);
        }
        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();
                });
            });
        }
Example #6
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();
                });
            });
        }
Example #7
0
//		static CCVerticalTextAlignment vertical;
//		static CCTextAlignment horizontal;

        // Used for debuggin purposes
        internal static void SaveToFile(string fileName, CGBitmapContext bitmap)
        {
            if (bitmap == null)
            {
                throw new ObjectDisposedException("cgimage");
            }

            // With MonoTouch we can use UTType from CoreMobileServices but since
            // MonoMac does not have that yet (or at least can not find it) I will
            // use the string version of those for now.  I did not want to add another
            // #if #else in here.

            // for now we will just default this to png
            var typeIdentifier = "public.png";

            // * NOTE * we only support one image for right now.
            //NSMutableData imgData = new NSMutableData();
            NSUrl url = NSUrl.FromFilename(fileName);

            // Create an image destination that saves into the imgData
            #if IOS
            CGImageDestination dest = CGImageDestination.Create(url, typeIdentifier, 1);
            #else
            CGImageDestination dest = CGImageDestination.FromUrl(url, typeIdentifier, 1);
            #endif

            // Add an image to the destination
            dest.AddImage(bitmap.GetImage(), (NSDictionary)null);

            // Finish the export
            //bool success = dest.Close ();
            //                        if (success == false)
            //                                Console.WriteLine("did not work");
            //                        else
            //                                Console.WriteLine("did work: " + path);

            dest.Dispose();
            dest = null;
        }
Example #8
0
        bool TryAddFrame(CGImageDestination dest, int frame)
        {
            try
            {
                var corrupted = imageSource != null && imageSource.GetPropertiesSafe(frame) == null;
                if (frame != currentFrame && imageSource != null && !corrupted)
                {
                    InitializeImageFrame(frame);
                }

                if (!corrupted)
                {
                    dest.AddImage(NativeCGImage, (NSDictionary)null);
                }

                return(true);
            }
            catch (Exception e)
            {
                Debug.Assert(false, "Failed adding destination: " + e.ToString());
                return(false);
            }
        }
Example #9
0
        private void Save(CGImageDestination dest)
        {
            if (NativeCGImage == null)
            {
                throw new ObjectDisposedException("cgimage");
            }

            int framesSaved = 0;
            int savedFrame  = currentFrame;

            for (int frame = 0; frame < frameCount; frame++)
            {
                var corrupted = imageSource != null && imageSource.GetPropertiesSafe(frame) == null;
                if (frame != currentFrame && imageSource != null && !corrupted)
                {
                    InitializeImageFrame(frame);
                }

                if (!corrupted)
                {
                    dest.AddImage(NativeCGImage, (NSDictionary)null);
                    ++framesSaved;
                }
            }
            if (currentFrame != savedFrame)
            {
                InitializeImageFrame(savedFrame);
            }

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

            dest.Close();
        }
Example #10
0
        private void Save(CGImageDestination dest)
        {
            if (NativeCGImage == null)
            {
                throw new ObjectDisposedException("cgimage");
            }

            int savedFrame = currentFrame;

            for (int frame = 0; frame < frameCount; frame++)
            {
                if (frame != currentFrame && imageSource != null)
                {
                    InitializeImageFrame(frame);
                }
                dest.AddImage(NativeCGImage, (NSDictionary)null);
            }
            if (currentFrame != savedFrame)
            {
                InitializeImageFrame(savedFrame);
            }

            dest.Close();
        }
Example #11
0
            void CameraImageCaptured(object sender, UIImagePickerMediaPickedEventArgs e)
            {
                bool   result    = false;
                string imagePath = null;

                // create a url of the path for the file to write
                NSUrl imageDestUrl = NSUrl.CreateFileUrl(new string[] { ImageDest });

                // create a CGImage destination that converts the image to jpeg
                CGImageDestination cgImageDest = CGImageDestination.Create(imageDestUrl, MobileCoreServices.UTType.JPEG, 1);

                if (cgImageDest != null)
                {
                    // note: the edited image is saved "correctly", so we don't have to rotate.

                    // rotate the image 0 degrees since we consider portrait to be the default position.
                    CIImage ciImage = new CIImage(e.OriginalImage.CGImage);

                    float rotationDegrees = 0.00f;
                    switch (e.OriginalImage.Orientation)
                    {
                    case UIImageOrientation.Up:
                    {
                        // don't do anything. The image space and the user space are 1:1
                        break;
                    }

                    case UIImageOrientation.Left:
                    {
                        // the image space is rotated 90 degrees from user space,
                        // so do a CCW 90 degree rotation
                        rotationDegrees = 90.0f;
                        break;
                    }

                    case UIImageOrientation.Right:
                    {
                        // the image space is rotated -90 degrees from user space,
                        // so do a CW 90 degree rotation
                        rotationDegrees = -90.0f;
                        break;
                    }

                    case UIImageOrientation.Down:
                    {
                        rotationDegrees = 180;
                        break;
                    }
                    }

                    // create our transform and apply it to the image
                    CGAffineTransform transform = CGAffineTransform.MakeIdentity( );
                    transform.Rotate(rotationDegrees * Rock.Mobile.Math.Util.DegToRad);
                    CIImage rotatedImage = ciImage.ImageByApplyingTransform(transform);

                    // create a context and render it back out to a CGImage. (Cast to ints so we account for any floating point error)
                    CIContext ciContext      = CIContext.FromOptions(null);
                    CGImage   rotatedCGImage = ciContext.CreateCGImage(rotatedImage, new System.Drawing.RectangleF((int)rotatedImage.Extent.X,
                                                                                                                   (int)rotatedImage.Extent.Y,
                                                                                                                   (int)rotatedImage.Extent.Width,
                                                                                                                   (int)rotatedImage.Extent.Height));

                    // put the image in the destination, converting it to jpeg.
                    cgImageDest.AddImage(rotatedCGImage);


                    // close and dispose.
                    if (cgImageDest.Close( ))
                    {
                        result    = true;
                        imagePath = ImageDest;

                        cgImageDest.Dispose( );
                    }
                }

                CameraFinishedCallback(result, imagePath);
            }
Example #12
0
        public void Save(string path, ImageFormat format)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            if (NativeCGImage == null)
            {
                throw new ObjectDisposedException("cgimage");
            }

            // With MonoTouch we can use UTType from CoreMobileServices but since
            // MonoMac does not have that yet (or at least can not find it) I will
            // use the string version of those for now.  I did not want to add another
            // #if #else in here.


            // for now we will just default this to png
            var typeIdentifier = "public.png";

            // Get the correct type identifier
            if (format == ImageFormat.Bmp)
            {
                typeIdentifier = "com.microsoft.bmp";
            }
//			else if (format == ImageFormat.Emf)
//				typeIdentifier = "image/emf";
//			else if (format == ImageFormat.Exif)
//				typeIdentifier = "image/exif";
            else if (format == ImageFormat.Gif)
            {
                typeIdentifier = "com.compuserve.gif";
            }
            else if (format == ImageFormat.Icon)
            {
                typeIdentifier = "com.microsoft.ico";
            }
            else if (format == ImageFormat.Jpeg)
            {
                typeIdentifier = "public.jpeg";
            }
            else if (format == ImageFormat.Png)
            {
                typeIdentifier = "public.png";
            }
            else if (format == ImageFormat.Tiff)
            {
                typeIdentifier = "public.tiff";
            }
            else if (format == ImageFormat.Wmf)
            {
                typeIdentifier = "com.adobe.pdf";
            }

            // Not sure what this is yet
            else if (format == ImageFormat.MemoryBmp)
            {
                throw new NotImplementedException("ImageFormat.MemoryBmp not supported");
            }

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

            // * NOTE * we only support one image for right now.

            // Create an image destination that saves into the path that is passed in
            CGImageDestination dest = CGImageDestination.FromUrl(url, typeIdentifier, imageCount, null);

            // Add an image to the destination
            dest.AddImage(NativeCGImage, null);

            // Finish the export
            bool success = dest.Close();

//                        if (success == false)
//                                Console.WriteLine("did not work");
//                        else
//                                Console.WriteLine("did work: " + path);
            dest.Dispose();
            dest = null;
        }