コード例 #1
0
        private async Task SaveAsync()
        {
            var stream = new InMemoryRandomAccessStream();
            await ImageCropper.SaveAsync(stream, BitmapFileFormat.Png);

            App.ViewModel.IsLoading = true;
            var dispatcherQueue = Windows.System.DispatcherQueue.GetForCurrentThread();
            var data            = await App.Repository.User.UploadAvatarAsync(stream, async res =>
            {
                await dispatcherQueue.EnqueueAsync(() =>
                {
                    App.ViewModel.IsLoading = false;
                    _ = new MessageDialog(res.Message ?? Constants.GetString("unknow_error")).ShowAsync();
                });
            });

            stream.Dispose();
            await dispatcherQueue.EnqueueAsync(() =>
            {
                App.ViewModel.IsLoading = false;
                if (data == null)
                {
                    return;
                }
                App.ViewModel.User = data;
                Frame.GoBack();
            });
        }
コード例 #2
0
        private async Task PickImage()
        {
            var filePicker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = PickerLocationId.PicturesLibrary,
                FileTypeFilter         =
                {
                    ".png", ".jpg", ".jpeg"
                }
            };
            var file = await filePicker.PickSingleFileAsync();

            if (file != null && ImageCropper != null)
            {
                await ImageCropper.LoadImageFromFile(file);

                return;
            }
            var dispatcherQueue = Windows.System.DispatcherQueue.GetForCurrentThread();
            await dispatcherQueue.EnqueueAsync(() =>
            {
                Frame.GoBack();
            });
        }
コード例 #3
0
        private static async void Finalize(ImageCropper imageCropper, UIImage image)
        {
            string  documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string  jpgFilename        = System.IO.Path.Combine(documentsDirectory, Guid.NewGuid().ToString() + ".jpg");
            NSData  imgData            = image.AsJPEG();
            NSError err;

            // small delay
            await System.Threading.Tasks.Task.Delay(TimeSpan.FromMilliseconds(100));

            if (imgData.Save(jpgFilename, false, out err))
            {
                imageCropper.Success?.Invoke(jpgFilename);
            }
            else
            {
                Debug.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
                imageCropper.Faiure?.Invoke();
            }
            //UIApplication.SharedApplication.KeyWindow.RootViewController.DismissViewController(true, null);
            UIWindow         window         = UIApplication.SharedApplication.KeyWindow;
            UIViewController viewController = window.RootViewController;

            while (viewController.PresentedViewController != null)
            {
                viewController = viewController.PresentedViewController;
            }
            viewController.DismissViewController(true, null);
        }
コード例 #4
0
        public void TestCropArc()
        {
            var srcImage = new IndexedImage {
                Size = new Size(10, 10)
            };

            int[] pixels;
            using (srcImage.LockPixels(out pixels))
            {
                for (int i = 0; i < pixels.Length; i++)
                {
                    pixels[i] = 100;
                }
            }

            var dstImage = ImageCropper.Crop(srcImage, new Rectangle(1, 1, 8, 8), ImageCropper.CropKind.Arc);

            dstImage.CompletePalette();

            Assert.AreEqual(new Size(8, 8), dstImage.Size);
            Assert.AreEqual(new Color(255, 255, 255), dstImage[0, 0]);
            Assert.AreEqual(new Color(255, 255, 255), dstImage[0, 7]);
            Assert.AreEqual(new Color(255, 255, 255), dstImage[7, 0]);
            Assert.AreEqual(new Color(255, 255, 255), dstImage[7, 7]);
            Assert.AreEqual(new Color(100), dstImage[4, 4], "Some point in the centre");
        }
コード例 #5
0
        public void ShowFromFile(ImageCropper imageCropper, string imageFile)
        {
            try {
                var activityBuilder = CropImage.Activity(Android.Net.Uri.FromFile(new Java.IO.File(imageFile)));
                var shape           = imageCropper.CropShape == ImageCropper.CropShapeType.Oval
                    ? CropImageView.CropShape.Oval
                    : CropImageView.CropShape.Rectangle;
                activityBuilder.SetCropShape(shape);

                if (imageCropper.AspectRatioX > 0 && imageCropper.AspectRatioY > 0)
                {
                    activityBuilder.SetFixAspectRatio(true);
                    activityBuilder.SetAspectRatio(imageCropper.AspectRatioX, imageCropper.AspectRatioY);
                }
                else
                {
                    activityBuilder.SetFixAspectRatio(false);
                }

                if (!string.IsNullOrWhiteSpace(imageCropper.PageTitle))
                {
                    activityBuilder.SetActivityTitle(imageCropper.PageTitle);
                }

                activityBuilder.Start(CrossCurrentActivity.Current.Activity);
            }
            catch (Exception ex) {
                Console.WriteLine(ex.ToString());
            }
        }
コード例 #6
0
ファイル: ImageProcessor.cs プロジェクト: manjacat/RPS.Photo
 private static Bitmap DrawRectangleToImage(Bitmap img,
                                            List <RectangleModel> rectangles)
 {
     using (Graphics gr = Graphics.FromImage(img))
     {
         foreach (var r in rectangles)
         {
             Rectangle rect1      = ConvertToRectangle(r);
             Bitmap    croppedImg = ImageCropper.CropImage(img, rect1);
             if (r.ObjectType == ObjectTypeEnum.Face)
             {
                 croppedImg = Blur(croppedImg, 6);
                 gr.DrawImage(croppedImg, rect1);
             }
             else if (r.ObjectType == ObjectTypeEnum.Licenseplate)
             {
                 croppedImg = Blur(croppedImg, 8);
                 gr.DrawImage(croppedImg, rect1);
             }
         }
     }
     return(img);
     //img.Save(outputfileName, ImageFormat.Jpeg);
     //Console.WriteLine("OUTPUT file is at " + outputFile);
 }
コード例 #7
0
        private async void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            var picker = new FileSavePicker
            {
                SuggestedStartLocation = PickerLocationId.PicturesLibrary,
                SuggestedFileName      = "Crop_Image"
            };

            picker.FileTypeChoices.Add("Png Picture", new List <string> {
                ".png", ".jpg"
            });
            var file = await picker.PickSaveFileAsync();

            if (file != null)
            {
                if (file.Name.Contains(".png"))
                {
                    await ImageCropper.SaveCroppedBitmapAsync(file, BitmapEncoder.PngEncoderId);
                }
                else
                {
                    await ImageCropper.SaveCroppedBitmapAsync(file, BitmapEncoder.JpegEncoderId);
                }
            }
        }
コード例 #8
0
        public void TestCropRect()
        {
            var srcImage = new IndexedImage {
                Size = new Size(5, 5)
            };

            int[] pixels;
            using (srcImage.LockPixels(out pixels))
            {
                for (int i = 0; i < pixels.Length; i++)
                {
                    pixels[i] = i;
                }
            }

            var dstImage = ImageCropper.Crop(srcImage, new Rectangle(2, 1, 2, 3), ImageCropper.CropKind.Rectangle);

            Assert.AreEqual(new Size(2, 3), dstImage.Size);
            using (dstImage.LockPixels(out pixels))
            {
                Assert.AreEqual(6, pixels.Length);
                Assert.AreEqual(7, pixels[0]);
                Assert.AreEqual(8, pixels[1]);
                Assert.AreEqual(12, pixels[2]);
                Assert.AreEqual(13, pixels[3]);
                Assert.AreEqual(17, pixels[4]);
                Assert.AreEqual(18, pixels[5]);
            }
        }
コード例 #9
0
        private async void SelectFromGalleryButtonClick(object sender, RoutedEventArgs e)
        {
            FileOpenPicker openPicker = new FileOpenPicker();

            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".bmp");
            //openPicker.FileTypeFilter.Add(".gif");
            openPicker.FileTypeFilter.Add(".png");
            StorageFile imgFile = await openPicker.PickSingleFileAsync();

            if (imgFile != null)
            {
                Helper.CreateCachedFolder();
                Helper.CreateCachedFolder();
                Helper.CreateCachedFolder();
                Helper.CreateCachedFolder();
                //var wb = new WriteableBitmap(1, 1);
                ShowEditor();
                //await wb.LoadAsync(imgFile);
                //ImageCropper.SourceImage = wb;
                ImageCropper.AspectRatio = 1d;
                ImageCropper.CropShape   = CropShape.Circular;
                await ImageCropper.LoadImageFromFile(imgFile);
            }
        }
コード例 #10
0
ファイル: CrossPainter.cs プロジェクト: MykolaKovalchuk/SAE5
        internal IndexedImage GetCross(int color)
        {
            var index      = random.Next(CrossesPerWhiteImage);
            var row        = index / CrossesPerWhiteImageGridSize;
            var col        = index % CrossesPerWhiteImageGridSize;
            var crossImage = ImageCropper.Crop(GetCrossesImage(color), new Rectangle(col * PixelHeight, row * PixelHeight, PixelHeight, PixelHeight));

            return(crossImage);
        }
コード例 #11
0
        private void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (mImageCrop != null)
            {
                mImageCrop = null;
            }

            mImageCrop = new ImageCropper(new Bitmap(this.pictureBox1.Image));
        }
コード例 #12
0
        public void ShowFromFile(ImageCropper imageCropper, string imageFile)
        {
            UIImage image = UIImage.FromFile(imageFile);

            TOCropViewController cropViewController;

            if (imageCropper.CropShape == ImageCropper.CropShapeType.Oval)
            {
                cropViewController = new TOCropViewController(TOCropViewCroppingStyle.Circular, image);
            }
            else
            {
                cropViewController = new TOCropViewController(image);
            }

            if (imageCropper.AspectRatioX > 0 && imageCropper.AspectRatioY > 0)
            {
                cropViewController.AspectRatioPreset       = TOCropViewControllerAspectRatioPreset.Custom;
                cropViewController.ResetAspectRatioEnabled = false;
                cropViewController.AspectRatioLockEnabled  = true;
                cropViewController.CustomAspectRatio       = new CGSize(imageCropper.AspectRatioX, imageCropper.AspectRatioY);
            }

            cropViewController.OnDidCropToRect = (outImage, cropRect, angle) =>
            {
                Finalize(imageCropper, outImage);
            };

            cropViewController.OnDidCropToCircleImage = (outImage, cropRect, angle) =>
            {
                Finalize(imageCropper, outImage);
            };

            cropViewController.OnDidFinishCancelled = (cancelled) =>
            {
                imageCropper.Faiure?.Invoke();
                UIApplication.SharedApplication.KeyWindow.RootViewController.DismissViewController(true, null);
            };

            //UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(cropViewController, true, null);
            // Patch for Modal iOS: https://github.com/stormlion227/ImageCropper.Forms/issues/22
            UIWindow         window         = UIApplication.SharedApplication.KeyWindow;
            UIViewController viewController = window.RootViewController;

            while (viewController.PresentedViewController != null)
            {
                viewController = viewController.PresentedViewController;
            }
            viewController.PresentViewController(cropViewController, true, null);
            // end on iOS Modal patch

            if (!string.IsNullOrWhiteSpace(imageCropper.PageTitle) && cropViewController.TitleLabel != null)
            {
                UILabel titleLabel = cropViewController.TitleLabel;
                titleLabel.Text = imageCropper.PageTitle;
            }
        }
コード例 #13
0
        public void cropTest()
        {
            ImageCropper ic = new ImageCropper(Image.FromFile("testResources/test.png"));

            Image im = ic.crop(20, 20, 10, 10);

            Assert.AreEqual(10, im.Width);
            Assert.AreEqual(10, im.Height);
        }
コード例 #14
0
    private static bool TryHandleState(
        State state,
        string folderPath,
        ResourceHandlePath resourceHandlePath,
        int imageCroppingLevel,
        out Exported.State exportedState)
    {
        exportedState = default;
        TextureSource textureSource = state.GetComponent<TextureSource>();
        if (textureSource == null)
        {
            EditorUtility.DisplayDialog("Error", "State has no texture source!", "Ok");
            return false;
        }

        var stateId = state.GetExportedId();

        var textureFileLocation = textureSource.GetAssetPath();
        string url = null;
        string croppedImageUrl = null;
        switch (resourceHandlePath)
        {
            case ResourceHandlePath.CopyToDist:
                var stateFolderPath = Path.Combine(folderPath, stateId);
                ImageCropper.HandleImage(textureFileLocation, stateFolderPath, imageCroppingLevel);
                croppedImageUrl = stateId;
                break;
            case ResourceHandlePath.PublishPath:
                url = textureFileLocation;
                if (url.StartsWith("Packages"))
                {
                    EditorUtility.DisplayDialog("Error",
                        "You can't use texture from Packages while preview. Please use textures only from Assets",
                        "Ok");
                    return false;
                }

                break;
            default:
                throw new Exception($"incorrect ResourceHandlePath {resourceHandlePath}");
        }

        exportedState = new Exported.State
        {
            id = stateId,
            title = state.title,
            url = url,
            croppedImageUrl = croppedImageUrl,
            type = textureSource.SourceType.ToString().ToLower(),
            pictureRotation = state.transform.rotation,
            links = GetLinks(state),
            groupLinks = GetGroupLinks(state),
            fieldItems = GetFieldItems(state, folderPath, resourceHandlePath)
        };
        return true;
    }
コード例 #15
0
        public void TestIsPointInsideArc()
        {
            var cropRect = new Rectangle(1, 1, 8, 8);

            Assert.IsFalse(ImageCropper.IsPointInsideArc(new Point(0, 0), cropRect));
            Assert.IsFalse(ImageCropper.IsPointInsideArc(new Point(0, 7), cropRect));
            Assert.IsFalse(ImageCropper.IsPointInsideArc(new Point(7, 0), cropRect));
            Assert.IsFalse(ImageCropper.IsPointInsideArc(new Point(7, 7), cropRect));
            Assert.IsTrue(ImageCropper.IsPointInsideArc(new Point(4, 4), cropRect), "Some point in the centre");
        }
コード例 #16
0
        public async void OnXamlRendered(FrameworkElement control)
        {
            _imageCropper = control.FindChild("ImageCropper") as ImageCropper;
            if (_imageCropper != null)
            {
                var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Photos/Owl.jpg"));

                await _imageCropper.LoadImageFromFile(file);
            }
        }
コード例 #17
0
        //private double AspectRatio = 1.91d;
        //private void ComboAspectRatioSelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    try
        //    {
        //        if(ComboAspectRatio.SelectedIndex != -1)
        //        {
        //            switch(ComboAspectRatio.SelectedIndex)
        //            {
        //                case 0:
        //                    AspectRatio = 1.91d;
        //                    ImageCropper.AspectRatio = AspectRatio;
        //                    break;

        //                case 1:
        //                    AspectRatio = 1d;
        //                    ImageCropper.AspectRatio = AspectRatio;
        //                    break;

        //                case 2:
        //                    AspectRatio = 0.8d;
        //                    ImageCropper.AspectRatio = AspectRatio;
        //                    break;

        //            }
        //        }
        //    }
        //    catch { }
        //}

        private async void CropButtonClick(object sender, RoutedEventArgs e)
        {
            try
            {
                Helper.CreateCachedFolder();
                Helper.CreateCachedFolder();
                Helper.CreateCachedFolder();
                if (IsVideo)
                {
                    using (var fileStream = await ThumbnailFile.OpenAsync(FileAccessMode.ReadWrite, StorageOpenOptions.None))
                        await ImageCropper.SaveAsync(fileStream, BitmapFileFormat.Jpeg);
                    ThumbnailFile = await new PhotoHelper().SaveToImage(ThumbnailFile, false);
                    var decoder = await BitmapDecoder.CreateAsync(await ThumbnailFile.OpenReadAsync());

                    VideoBitmapDecoder         = decoder;
                    CurrentCroppedRectForVideo = ImageCropper.CurrentCroppedRect;
                    ShowImagePreview(ThumbnailFile);
                    UploadButton.IsEnabled = true;
                }
                else
                {
                    var cacheFolder = await SessionHelper.LocalFolder.GetFolderAsync("Cache");

                    var file = await cacheFolder.CreateFileAsync(15.GenerateRandomStringStatic() + ".jpg");

                    //await ImageCropper.CroppedImage.SaveAsync(file);
                    using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite, StorageOpenOptions.None))
                        await ImageCropper.SaveAsync(fileStream, BitmapFileFormat.Jpeg);
                    FileToUpload = await new PhotoHelper().SaveToImage(file, false, false);

                    //CropGrid.Visibility = Visibility.Collapsed;
                    ShowImagePreview(FileToUpload);
                    UploadButton.IsEnabled = true;
                }



                //using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite, StorageOpenOptions.None))
                //    await ImageCropper.SaveAsync(fileStream, BitmapFileFormat.Jpeg);
                //ThumbnailFile = await new PhotoHelper().SaveToImage(file, false);

                ////CropGrid.Visibility = Visibility.Collapsed;
                //ShowImagePreview(ThumbnailFile);
                //var converter = new VideoConverter();
                //var decoder = await BitmapDecoder.CreateAsync(await ThumbnailFile.OpenReadAsync());

                //var converted = await converter.ConvertFiles(new List<StorageFile> { FileToUpload }, false, new Size(decoder.PixelWidth, decoder.PixelHeight));
            }
            catch (Exception ex)
            {
                ex.PrintException("CropButtonClick");
            }
        }
コード例 #18
0
 private async void PickImgButton_Click(object sender, RoutedEventArgs e)
 {
     var openPicker = new FileOpenPicker
     {
         ViewMode = PickerViewMode.Thumbnail,
         SuggestedStartLocation = PickerLocationId.PicturesLibrary
     };
     openPicker.FileTypeFilter.Add(".png");
     openPicker.FileTypeFilter.Add(".jpg");
     openPicker.FileTypeFilter.Add(".jpeg");
     var file = await openPicker.PickSingleFileAsync();
     if (file != null)
         await ImageCropper.LoadImageFromFile(file);
 }
コード例 #19
0
        async void ImportFile(StorageFile file)
        {
            try
            {
                var    editNeeded = false;
                double width = 0, height = 0;
                var    decoder = await BitmapDecoder.CreateAsync(await file.OpenReadAsync());

                width  = decoder.PixelWidth;
                height = decoder.PixelHeight;
                var wRatio = AspectRatioHelper.GetAspectRatioForMedia(width, height);
                var hRatio = AspectRatioHelper.GetAspectRatioForMedia(height, width);
                //if (wRatio > 1.91 && wRatio < 0.8)
                //    editNeeded = true;
                //else
                //{
                //    if (hRatio > 1.91 && hRatio < 0.8)
                //        editNeeded = true;
                //}
                //if (height > width)
                editNeeded = true;

                if (!editNeeded)
                {
                    CropGrid.Visibility    = Visibility.Visible;
                    ImageView.Visibility   = Visibility.Collapsed;
                    UploadButton.IsEnabled = false;

                    AspectRatioSlider.Value  = wRatio;
                    ImageCropper.AspectRatio = wRatio;
                    ImageCropper.CropShape   = CropShape.Rectangular;
                    await ImageCropper.LoadImageFromFile(file);
                }
                else
                {
                    CropGrid.Visibility    = Visibility.Visible;
                    ImageView.Visibility   = Visibility.Collapsed;
                    UploadButton.IsEnabled = false;
                    //Helper.ShowNotify("Your photo is not in a acceptable aspect ratio." +
                    //    "\r\nYou need to crop it and then you can upload it.", 4500);


                    AspectRatioSlider.Value  = DefaultAspectRatio;
                    ImageCropper.AspectRatio = DefaultAspectRatio;
                    ImageCropper.CropShape   = CropShape.Rectangular;
                    await ImageCropper.LoadImageFromFile(file);
                }
            }
            catch { }
        }
コード例 #20
0
        public void ShowFromFile(ImageCropper imageCropper, string imageFile)
        {
            UIImage image = UIImage.FromFile(imageFile);

            TOCropViewController cropViewController;

            if (imageCropper.CropShape == ImageCropper.CropShapeType.Oval)
            {
                cropViewController = new TOCropViewController(TOCropViewCroppingStyle.Circular, image);
            }
            else
            {
                cropViewController = new TOCropViewController(image);
            }
            cropViewController.DoneButtonTitle   = imageCropper.CropButtonTitle;
            cropViewController.CancelButtonTitle = imageCropper.CancelButtonTitle;

            if (imageCropper.AspectRatioX > 0 && imageCropper.AspectRatioY > 0)
            {
                cropViewController.AspectRatioPreset       = TOCropViewControllerAspectRatioPreset.Custom;
                cropViewController.ResetAspectRatioEnabled = false;
                cropViewController.AspectRatioLockEnabled  = true;
                cropViewController.CustomAspectRatio       = new CGSize(imageCropper.AspectRatioX, imageCropper.AspectRatioY);
            }

            cropViewController.OnDidCropToRect = (outImage, cropRect, angle) =>
            {
                Finalize(imageCropper, outImage);
            };

            cropViewController.OnDidCropToCircleImage = (outImage, cropRect, angle) =>
            {
                Finalize(imageCropper, outImage);
            };

            cropViewController.OnDidFinishCancelled = (cancelled) =>
            {
                imageCropper.Faiure?.Invoke();
                UIApplication.SharedApplication.KeyWindow.RootViewController.DismissViewController(true, null);
            };

            UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(cropViewController, true, null);

            if (!string.IsNullOrWhiteSpace(imageCropper.PageTitle) && cropViewController.TitleLabel != null)
            {
                UILabel titleLabel = cropViewController.TitleLabel;
                titleLabel.Text = imageCropper.PageTitle;
            }
        }
コード例 #21
0
        private async void OkImageButtonClick(object sender, RoutedEventArgs e)
        {
            try
            {
                ShowLoading();
                var cacheFolder = await SessionHelper.LocalFolder.GetFolderAsync("Cache");

                var file = await cacheFolder.CreateFileAsync(15.GenerateRandomStringStatic() + ".jpg");

                using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite, StorageOpenOptions.None))
                    await ImageCropper.SaveAsync(fileStream, UI.Controls.BitmapFileFormat.Jpeg);
                var fileToUpload = await new PhotoHelper().SaveToImage(file);
                Uploader.UploadSinglePhoto(fileToUpload);
            }
            catch { }
        }
コード例 #22
0
ファイル: UploadUc.xaml.cs プロジェクト: xuan2261/Minista
        private async void CropButtonClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!CanCrop)
                {
                    Helper.ShowNotify("Please wait a few more seconds....");
                    return;
                }
                Helper.CreateCachedFolder();
                Helper.CreateCachedFolder();
                Helper.CreateCachedFolder();
                if (IsVideo)
                {
                    using (var fileStream = await ThumbnailFile.OpenAsync(FileAccessMode.ReadWrite, StorageOpenOptions.None))
                        await ImageCropper.SaveAsync(fileStream, BitmapFileFormat.Jpeg);
                    ThumbnailFile = await new PhotoHelper().SaveToImage(ThumbnailFile, false);
                    var decoder = await BitmapDecoder.CreateAsync(await ThumbnailFile.OpenReadAsync());

                    BitmapDecoder = decoder;
                    CurrentCroppedRectForVideo = ImageCropper.CurrentCroppedRect;
                    ShowImagePreview(ThumbnailFile);
                }
                else
                {
                    var cacheFolder = await SessionHelper.LocalFolder.GetFolderAsync("Cache");

                    var file = await cacheFolder.CreateFileAsync(15.GenerateRandomStringStatic() + ".jpg");

                    //await ImageCropper.CroppedImage.SaveAsync(file);
                    using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite, StorageOpenOptions.None))
                        await ImageCropper.SaveAsync(fileStream, BitmapFileFormat.Jpeg);
                    FileToUpload = await new PhotoHelper().SaveToImage(file, false, false);

                    var decoder = await BitmapDecoder.CreateAsync(await FileToUpload.OpenReadAsync());

                    BitmapDecoder = decoder;
                    //CropGrid.Visibility = Visibility.Collapsed;
                    ShowImagePreview(FileToUpload);
                }
                Editing = false;
            }
            catch (Exception ex)
            {
                ex.PrintException("CropButtonClick");
            }
        }
コード例 #23
0
        private static async Task CropImageFile(StorageFile imageFile, Size imageSize, CropMethod method, Size screenSize, IBuffer previewBuffer)
        {
            switch (method)
            {
            case CropMethod.None:
                break;

            case CropMethod.Center:
            {
                var cropRect = CropBitmap.GetCenterCropRect(imageSize, screenSize);
                await CropBitmap.GetCroppedBitmapAsync(imageFile, cropRect, 1.0);
            }
            break;

            case CropMethod.TopMiddle:
            {
                var cropRect = CropBitmap.GetTopMiddleCropRect(imageSize, screenSize);
                await CropBitmap.GetCroppedBitmapAsync(imageFile, cropRect, 1.0);
            }
            break;

            case CropMethod.MostFaces:
            case CropMethod.BiggestFace:
                var result = await DetechFromBufferAsync(previewBuffer, 3, 25);

                var faces = ImageCropper.ScaleFaces(result.Faces, imageSize, result.FrameSize);
                if (faces.Count() > 0)
                {
                    if (method == CropMethod.BiggestFace)
                    {
                        faces = faces.OrderByDescending(o => o.Width).Take(1);
                    }
                    var cropRect = CropBitmap.GetGreedyCropRect(imageSize, screenSize, faces);
                    await CropBitmap.GetCroppedBitmapAsync(imageFile, cropRect, 1.0);
                }
                else
                {
                    // No face detected, fall back crop
                    var cropRect = CropBitmap.GetTopMiddleCropRect(imageSize, screenSize);
                    await CropBitmap.GetCroppedBitmapAsync(imageFile, cropRect, 1.0);
                }
                break;

            default:
                break;
            }
        }
コード例 #24
0
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/test.jpg"));

            await ImageCropper.LoadImageFromFile(file);

            var itemSource = new List <AspectRatioConfig>
            {
                new AspectRatioConfig
                {
                    Name        = "Custom",
                    AspectRatio = -1
                },
                new AspectRatioConfig
                {
                    Name        = "Square",
                    AspectRatio = 1
                },
                new AspectRatioConfig
                {
                    Name        = "Landscape(16:9)",
                    AspectRatio = 16d / 9d
                },
                new AspectRatioConfig
                {
                    Name        = "Portrait(9:16)",
                    AspectRatio = 9d / 16d
                },
                new AspectRatioConfig
                {
                    Name        = "4:3",
                    AspectRatio = 4d / 3d
                },
                new AspectRatioConfig
                {
                    Name        = "3:2",
                    AspectRatio = 3d / 2d
                }
            };

            AspectRatioComboBox.ItemsSource       = itemSource;
            AspectRatioComboBox.DisplayMemberPath = "Name";
            AspectRatioComboBox.SelectedValuePath = "AspectRatio";
            AspectRatioComboBox.SelectedIndex     = 0;
            AspectRatioComboBox.SelectionChanged += this.AspectRatioComboBox_SelectionChanged;
        }
コード例 #25
0
 public SyncFusionImageCropper(Stream Imagestream = null)
 {
     InitializeComponent();
     ImageCropper.SetToolbarItemVisibility("Back, Text, Add, TextColor, FontFamily, Arial, Noteworthy, Marker Felt, Bradley Hand, SignPainter, Opacity, Path, StrokeThickness, Colors, Opacity, Shape, Rectangle, StrokeThickness, Circle, Arrow, Undo, Redo, Effects, Hue, Saturation, Brightness, Contrast, Blur and Sharpen", false);
     ImageCropper.ToggleCropping(new Rectangle(20, 20, 20, 20));
     if (Imagestream == null)
     {
         ImageCropper.Source = ImageSource.FromUri(new Uri("http://photos2.insidercdn.com/iphone4scamera-111004-full.JPG"));
     }
     else
     {
         ImageCropper.Source = ImageSource.FromStream(() =>
         {
             return(Imagestream);
         });
     }
 }
コード例 #26
0
        private void TrySetRegionButton_Click(object sender, RoutedEventArgs e)
        {
            var text = RegionTextBox.Text;

            if (!string.IsNullOrWhiteSpace(text))
            {
                var points = text.Replace(" ", "").Split(',');
                if (points.Length == 4)
                {
                    var x      = Int32.Parse(points[0]);
                    var y      = Int32.Parse(points[1]);
                    var width  = Int32.Parse(points[2]);
                    var height = Int32.Parse(points[3]);
                    var ret    = ImageCropper.TrySetCroppedRegion(new Rect(x, y, width, height));
                }
            }
        }
コード例 #27
0
        void Finalize(ImageCropper imageCropper, UIImage image)
        {
            string  documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string  jpgFilename        = System.IO.Path.Combine(documentsDirectory, Guid.NewGuid().ToString() + ".jpg");
            NSData  imgData            = image.AsJPEG();
            NSError err = null;

            if (imgData.Save(jpgFilename, false, out err))
            {
                imageCropper.Success?.Invoke(jpgFilename);
            }
            else
            {
                Debug.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
                imageCropper.Faiure?.Invoke();
            }
            UIApplication.SharedApplication.KeyWindow.RootViewController.DismissViewController(true, null);
        }
コード例 #28
0
        bool IsZoomedPixelInsideCropRect(int x, int y)
        {
            bool result = false;

            switch (CropKind)
            {
            case ImageCropper.CropKind.Arc:
                result = ImageCropper.IsPointInsideArc(new Point(x - CropRect.Left, y - CropRect.Top), CropRect);
                break;

            case ImageCropper.CropKind.Rectangle:
                result =
                    x >= CropRect.Left && x < CropRect.RightExclusive &&
                    y >= CropRect.Top && y < CropRect.BottomExclusive;
                break;
            }
            return(result);
        }
コード例 #29
0
        public async Task LoadFile(StorageFile file, bool innerCall = false)
        {
            if (!innerCall)
            {
                OriginalFile = file;
            }

            try
            {
                EditedFile = await new PhotoHelper().SaveToImage(file, false);
                AspectRatioSlider.Value  = AspectRatio;
                ImageCropper.AspectRatio = AspectRatio;
                ShowCropper(innerCall);
                ImageCropper.CropShape = CropShape.Rectangular;
                await ImageCropper.LoadImageFromFile(EditedFile);
            }
            catch { }
        }
コード例 #30
0
 protected override void UpdateVisualImageCore()
 {
     if (ZoomPercent == 100)
     {
         if (VisualImageFrame.Width == SourceImage.Size.Width && VisualImageFrame.Height == SourceImage.Size.Height)
         {
             VisualImage.Size = SourceImage.Size;
             SourceImage.Pixels.CopyTo(VisualImage.Pixels, 0);
         }
         else
         {
             ImageCropper.Crop(SourceImage, VisualImageFrame, ImageCropper.CropKind.Rectangle, VisualImage);
         }
     }
     else
     {
         new ImageResampler().Resample(SourceImage, ZoomedImageSize, ZoomPercent > 100 ? UpscaleFilterType : DownscaleFilterType, VisualImageFrame, VisualImage);
     }
 }