Esempio n. 1
0
        public string getPrediction(Plugin.Media.Abstractions.MediaFile image)
        {
            Task <Bitmap> temp   = getBitmap(image);
            Bitmap        bitmap = temp.Result;
            var           assets = Android.App.Application.Context.Assets;
            TensorFlowInferenceInterface inferenceInterface = new TensorFlowInferenceInterface(assets, "frozen_inference_graph.pb");
            var sr     = new StreamReader(assets.Open("labels.txt"));
            var labels = sr.ReadToEnd()
                         .Split('\n')
                         .Select(s => s.Trim())
                         .Where(s => !string.IsNullOrEmpty(s))
                         .ToList();
            var outputNames = new[] { "detection_classes" };
            var floatValues = GetBitmapPixels(bitmap);
            var outputs     = new float[labels.Count];

            inferenceInterface.Feed("ToFloat", floatValues, 1, 227, 227, 3);
            inferenceInterface.Run(outputNames);
            inferenceInterface.Fetch("detection_classes", outputs);

            var results = new List <Tuple <float, string> >();

            for (var i = 0; i < outputs.Length; ++i)
            {
                results.Add(Tuple.Create(outputs[i], labels[i]));
            }

            return(results.OrderByDescending(t => t.Item1).First().Item2);
        }
        private async void BtnPickPhoto_Clicked(object sender, EventArgs e)
        {
            if (CrossMedia.Current.IsPickPhotoSupported)
            {
                var file = await CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions()
                {
                    CompressionQuality = 40,
                    PhotoSize          = Plugin.Media.Abstractions.PhotoSize.Small,
                });

                mainFile = file;

                if (file == null)
                {
                    return;
                }
                imgProfilePicture.Source = ImageSource.FromStream(() =>
                {
                    var stream = file.GetStream();
                    //imgStream = stream;
                    //file.Dispose();
                    return(stream);
                });
                btnConfirm.IsEnabled       = true;
                btnConfirm.BackgroundColor = Color.FromHex("#71d18b");
            }
            else
            {
                await DisplayAlert("UYARI", "Uygun kamera mevcut değil!", "OK");

                return;
            }
        }
Esempio n. 3
0
        public string SaveFotoFromAlbum(string caminhoImagem, Plugin.Media.Abstractions.MediaFile file)
        {
            string nomeArquivo;

            if (string.IsNullOrEmpty(caminhoImagem) || caminhoImagem.StartsWith("http"))
            {
                nomeArquivo = String.Format("{0:ddMMyyy_HHmm}", DateTime.Now) + ".jpg";
            }
            else
            {
                if (File.Exists(DependencyService.Get <IFotoLoadMediaPlugin>().GetPathToPhoto(caminhoImagem)))
                {
                    File.Delete(DependencyService.Get <IFotoLoadMediaPlugin>().GetPathToPhoto(caminhoImagem));
                }
                nomeArquivo = (caminhoImagem.LastIndexOf("/") > 0) ? caminhoImagem.Substring(caminhoImagem.LastIndexOf("/") + 1) : caminhoImagem;
            }

            var caminhoFotos = DependencyService.Get <IFotoLoadMediaPlugin>().GetDevicePathToPhoto();

            if (!Directory.Exists(caminhoFotos))
            {
                Directory.CreateDirectory(caminhoFotos);
            }

            string caminhoCompleto = Path.Combine(caminhoFotos, nomeArquivo);

            using (FileStream fileStream = new FileStream(caminhoCompleto, FileMode.Create))
            {
                file.GetStream().CopyTo(fileStream);
            }
            return(DependencyService.Get <IFotoLoadMediaPlugin>().SetPathToPhoto(caminhoCompleto));
        }
        private async void EditIcon_Tabbed(object sender, EventArgs e)
        {
            await CrossMedia.Current.Initialize();

            if (!CrossMedia.Current.IsPickPhotoSupported)
            {
                await DisplayAlert("Alert", "not supprored", "ok");
            }
            var mediaoptions = new Plugin.Media.Abstractions.PickMediaOptions()
            {
                PhotoSize = PhotoSize.Medium
            };

            selectedimgfile = await CrossMedia.Current.PickPhotoAsync(mediaoptions);

            if (selectedimgfile == null)
            {
                await DisplayAlert("error", "tryagain", "ok");
            }
            else
            {
                UserImage.Source = ImageSource.FromStream(() => selectedimgfile.GetStream());
                Stream stream    = selectedimgfile.GetStream();
                var    imagePath = await UserProfileViewModel.UploadImage(stream, selectedimgfile.Path);

                var userID = int.Parse(Application.Current.Properties["UserID"].ToString());
                User.Image = imagePath;

                User = await UserProfileViewModel.EditUser(User, User.ID);

                UserImage.Source = App.ServiceURL + User.Image;
            }
        }
Esempio n. 5
0
 private void Remove_Image(object sender, EventArgs e)
 {
     imageFile                   = null;
     ImageGoiVay.Source          = null;
     BtnRemoveImage.IsVisible    = false;
     grImageGoiVay.IsVisible     = false;
     viewModel.GoiVayModel.Image = null;
 }
Esempio n. 6
0
        public async Task OpenPhotoTaker()
        {
            try
            {
                ActivateSpinner();

                var rnd       = new Random();
                var rndEnding = rnd.Next(100, 9999);
                if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
                {
                    await _userDialogs.AlertAsync("It appears that no camera is available", "No Camera", "OK");

                    return;
                }
                var myfile = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
                {
                    PhotoSize          = Plugin.Media.Abstractions.PhotoSize.Small,         //resizes the photo to 50% of the original
                    CompressionQuality = 92,                                                // Int from 0 to 100 to determine image compression level
                    DefaultCamera      = Plugin.Media.Abstractions.CameraDevice.Front,      // determine which camera to default to
                    Directory          = "CC Directors",
                    Name        = $"mybrulepic{rndEnding}",
                    SaveToAlbum = true,                                                     // this saves the photo to the camera roll
                                                                                            //if we need the public album path --> var aPpath = file.AlbumPath;
                                                                                            //if we need a private path --> var path = file.Path;
                    AllowCropping = false,
                });

                file = myfile;
                if (file == null)
                {
                    DeactivateSpinner();
                    return;
                }

                Debug.WriteLine("File Location: " + file.Path + "     <--- here");
                setImage = ImageSource.FromStream(() =>
                {
                    var stream      = file.GetStream();
                    var path        = file.Path;
                    var pathprivate = file.AlbumPath;
                    Debug.WriteLine(path.ToString());
                    Debug.WriteLine(pathprivate.ToString());
                    selectedImage = file.GetStream();

                    return(stream);
                });
                imageShowing = true;
                RaisePropertyChanged();

                WouldBruleLikeIt(file);
                DeactivateSpinner();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                DeactivateSpinner();
            }
        }
Esempio n. 7
0
        public async Task OpenPhotoSelecter()
        {
            try
            {
                ActivateSpinner();

                if (!CrossMedia.Current.IsPickPhotoSupported)
                {
                    await _userDialogs.AlertAsync("Permission was not granted to access camera roll or picking photos is not available on this device.", "Cannot Pick Photo", "OK");

                    return;
                }
                var myfile = await CrossMedia.Current.PickPhotoAsync(new PickMediaOptions
                {
                    PhotoSize          = PhotoSize.Small,
                    CompressionQuality = 92,
                });

                file = myfile;
                if (file == null)
                {
                    DeactivateSpinner();
                    return;
                }
                string filePath = file.Path;
                string fileType = filePath.Substring(filePath.Length - 4);
                Debug.WriteLine($"****    {fileType}   *****");
                if (fileType == ".jpg" || fileType == ".png" || fileType == ".JPG" || fileType == ".PNG")
                {
                    setImage = ImageSource.FromStream(() =>
                    {
                        var stream      = file.GetStream();
                        var path        = file.Path;
                        var pathprivate = file.AlbumPath;
                        Debug.WriteLine(path);
                        Debug.WriteLine(pathprivate);
                        selectedImage = file.GetStream();

                        //file.Dispose();
                        return(stream);
                    });
                    imageShowing = true;
                    RaisePropertyChanged();

                    WouldBruleLikeIt(file);
                    DeactivateSpinner();
                }
                else
                {
                    await _userDialogs.AlertAsync("Unsupported file type.", "Error", "OK");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                DeactivateSpinner();
            }
        }
 public PagePrincipal(Plugin.Media.Abstractions.MediaFile Foto)
 {
     InitializeComponent();
     MinhaImagem.Source = ImageSource.FromStream(() =>
     {
         var stream = Foto.GetStream();
         Foto.Dispose();
         return(stream);
     });
     //testeDB.Text = App.DbPath;
     Detail = new PageHome();
     bt_home_Clicked(new object(), new EventArgs());
 }
Esempio n. 9
0
        // update avatar to sql server and mongodb.
        async void UpdateAvatar(Plugin.Media.Abstractions.MediaFile file, string fileName)
        {
            if (file == null)
            {
                return;
            }
            viewModel.IsLoading = true;
            StreamContent content = new StreamContent(file.GetStream());

            content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name     = "files",
                FileName = fileName
            };

            MultipartFormDataContent form = new MultipartFormDataContent();

            form.Add(content);

            var apiResponse = await BsdHttpClient.Instance().PostAsync(ApiRouter.USER_AVATAR_UPLOAD, form);

            if (apiResponse.IsSuccessStatusCode)
            {
                string      AvatarUrl = "avatar/" + fileName;
                ApiResponse response  = await ApiHelper.Post(ApiRouter.USER_AVATAR_UPDATE, AvatarUrl, true, false);

                if (response.IsSuccess)
                {
                    viewModel.User.AvatarUrl = AvatarUrl;

                    string AvatarFullUrl = viewModel.User.AvatarFullUrl;

                    image.Source = AvatarFullUrl;
                    UserLogged.SaveAvatar(AvatarFullUrl);

                    MessagingCenter.Send <ProfilePage, string>(this, "UpdateAvatar", AvatarUrl);
                    await DisplayAlert("", Language.cap_nhat_anh_dai_dien_thanh_cong, Language.dong);
                }
                else
                {
                    await DisplayAlert("", Language.khong_cap_nhat_duoc_anh_dai_dien, Language.dong);
                }
            }
            else
            {
                await DisplayAlert("", Language.khong_cap_nhat_duoc_anh_dai_dien, Language.dong);
            }
            viewModel.IsLoading = false;
        }
Esempio n. 10
0
        private async void TakePhoneBtn_Clicked(object sender, EventArgs e)
        {
            Plugin.Media.Abstractions.StoreCameraMediaOptions options = new Plugin.Media.Abstractions.StoreCameraMediaOptions()
            {
                SaveToAlbum   = false,
                DefaultCamera = CameraDevice.Front,
            };
            mediaFile = await CrossMedia.Current.TakePhotoAsync(options);

            CameraImage.Source = ImageSource.FromStream(() =>
            {
                return(mediaFile.GetStream());
            });
            _imageStream = mediaFile.GetStream();
        }
Esempio n. 11
0
 private byte[] ResizeImage(Plugin.Media.Abstractions.MediaFile imageFile)
 {
     if (imageFile != null)
     {
         using (MemoryStream ms = new MemoryStream())
         {
             imageFile.GetStream().CopyTo(ms);
             byte[] bytes = ms.ToArray();
             return(bytes);
         }
     }
     else
     {
         return(null);
     }
 }
Esempio n. 12
0
        private async void Upload_Id_Clicked(object sender, EventArgs e)
        {
            ImageLayout.IsVisible = true;
            PickedID = await PickPhoto();

            if (PickedID != null)
            {
                IDImage.Source = PickedID.Path;
                IDbytes        = File.ReadAllBytes(PickedID.Path);
            }
            else
            {
                await DisplayAlert("Error", "Failed to pick image. Please try again", "Ok");

                IDImage.Source = null;
            }
        }
        private async void GetPhoto(bool isFromCamera)
        {
            try
            {
                await CrossMedia.Current.Initialize();


                if (isFromCamera)
                {
                    if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
                    {
                        DisplayAlert("No Camera", ":( No camera available.", "OK");
                        return;
                    }
                    profileData = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
                    {
                        Directory = "Sample",
                        Name      = "test.jpg"
                    });
                }
                else
                {
                    profileData = await CrossMedia.Current.PickPhotoAsync();
                }

                if (profileData == null)
                {
                    return;
                }
                imgProfile.IsVisible   = true;
                frameProfile.IsVisible = false;


                imgProfile.Source = ImageSource.FromStream(() =>
                {
                    var stream = profileData.GetStream();

                    return(stream);
                });
            }
            catch (Exception ex)
            {
            }
        }
Esempio n. 14
0
        private async void ChangeImage()
        {
            await CrossMedia.Current.Initialize();

            var source = await Application.Current.MainPage.DisplayActionSheet(
                Languages.ImageSource,
                Languages.Cancel,
                null,
                Languages.FromGallery,
                Languages.NewPicture);

            if (source == Languages.Cancel)
            {
                this.file = null;
                return;
            }

            if (source == Languages.NewPicture)
            {
                this.file = await CrossMedia.Current.TakePhotoAsync(
                    new StoreCameraMediaOptions
                {
                    Directory = "Sample",
                    Name      = "test.jpg",
                    PhotoSize = PhotoSize.Small,
                }
                    );
            }
            else
            {
                this.file = await CrossMedia.Current.PickPhotoAsync();
            }

            if (this.file != null)
            {
                this.ImageSource = ImageSource.FromStream(() =>
                {
                    var stream = file.GetStream();
                    return(stream);
                });
            }
        }
Esempio n. 15
0
        // take new photo from camera
        async Task TakePhoto()
        {
            await CrossMedia.Current.Initialize();

            if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
            {
                await DisplayAlert(Language.thong_bao, Language.may_anh_khong_kha_dung, Language.dong);

                return;
            }

            var fileName = $"{Guid.NewGuid().ToString()}.jpg";

            Plugin.Media.Abstractions.MediaFile file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
            {
                Name        = fileName,
                SaveToAlbum = false
            });

            //UpdateAvatar(file, fileName);
        }
        private async void AddUserPhoto_Tapped(object sender, EventArgs e)
        {
            await CrossMedia.Current.Initialize();

            if (!CrossMedia.Current.IsPickPhotoSupported)
            {
                await DisplayAlert("Alert", "not supprored", "ok");

                return;
            }
            var mediaoptions = new PickMediaOptions()
            {
                PhotoSize = PhotoSize.Medium
            };

            selectedimgfile = await CrossMedia.Current.PickPhotoAsync(mediaoptions);

            if (selectedimgfile == null)
            {
                await DisplayAlert("error", "tryagain", "ok");
            }
            image.Source = ImageSource.FromStream(() => selectedimgfile.GetStream());
        }
        private async void BtnTakePhoto_Clicked(object sender, EventArgs e)
        {
            if (CrossMedia.Current.IsCameraAvailable && CrossMedia.Current.IsTakePhotoSupported)
            {
                // Supply media options for saving our photo after it's taken.
                var mediaOptions = new Plugin.Media.Abstractions.StoreCameraMediaOptions
                {
                    Directory          = "MediaPlugin",
                    Name               = DateTime.Now + ".jpg",
                    DefaultCamera      = Plugin.Media.Abstractions.CameraDevice.Front,
                    SaveToAlbum        = false,
                    CompressionQuality = 40,
                    PhotoSize          = Plugin.Media.Abstractions.PhotoSize.Small
                };
                //mainFile = mediaOptions;


                // Take a photo of the business receipt.
                var file = await CrossMedia.Current.TakePhotoAsync(mediaOptions);

                mainFile = file;
                if (file == null)
                {
                    return;
                }
                imgProfilePicture.Source = ImageSource.FromStream(() =>
                {
                    var stream = file.GetStream();
                    //imgStream = stream;
                    //file.Dispose();

                    return(stream);
                });
                btnConfirm.IsEnabled       = true;
                btnConfirm.BackgroundColor = Color.FromHex("#71d18b");
            }
        }
Esempio n. 18
0
        private async void PickImage_Clicked(object sender, EventArgs e)
        {
            string action = await Shell.Current.DisplayActionSheet(Language.chon_hinh_dai_dien, Language.huy, null, Language.thu_vien_anh, Language.chup_hinh);

            if (action == Language.chup_hinh)
            {
                var cameraStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera);

                if (cameraStatus != PermissionStatus.Granted)
                {
                    if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Camera))
                    {
                        await Shell.Current.DisplayAlert(Language.quyen_truy_cap_may_anh, Language.sundihome_can_truy_cap_vao_may_anh_de_chup_hinh_goi_vay, Language.dong);
                    }
                    if (Device.RuntimePlatform == Device.iOS)
                    {
                        cameraStatus = await PermissionHelper.CheckPermissions(Permission.Camera, Language.quyen_truy_cap_may_anh, Language.sundihome_can_truy_cap_vao_may_anh_de_chup_hinh_goi_vay);
                    }
                    else
                    {
                        var response = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Camera);

                        if (response.ContainsKey(Permission.Camera))
                        {
                            cameraStatus = response[Permission.Camera];
                        }
                    }
                }
                if (cameraStatus == PermissionStatus.Granted)
                {
                    await CrossMedia.Current.Initialize();

                    if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
                    {
                        await Shell.Current.DisplayAlert("", Language.may_anh_khong_kha_dung, Language.dong);

                        return;
                    }

                    imageFile = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
                    {
                        SaveToAlbum = false
                    });

                    if (imageFile != null)
                    {
                        ImageGoiVay.Source       = imageFile.Path;
                        BtnRemoveImage.IsVisible = true;
                        grImageGoiVay.IsVisible  = true;
                    }
                }
            }
            if (action == Language.thu_vien_anh)
            {
                var photoStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Photos);

                if (photoStatus != PermissionStatus.Granted)
                {
                    if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Photos))
                    {
                        await Shell.Current.DisplayAlert(Language.quyen_truy_cap_thu_vien, Language.sundihome_can_truy_cap_vao_thu_vien_de_lay_hinh_anh_goi_vay, Language.dong);
                    }
                    if (Device.RuntimePlatform == Device.iOS)
                    {
                        photoStatus = await PermissionHelper.CheckPermissions(Permission.Photos, Language.quyen_truy_cap_thu_vien, Language.sundihome_can_truy_cap_vao_thu_vien_de_lay_hinh_anh_goi_vay);
                    }
                    else
                    {
                        var response = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Photos);

                        if (response.ContainsKey(Permission.Photos))
                        {
                            photoStatus = response[Permission.Photos];
                        }
                    }
                }
                if (photoStatus == PermissionStatus.Granted)
                {
                    if (!CrossMedia.Current.IsPickPhotoSupported)
                    {
                        await Shell.Current.DisplayAlert(Language.quyen_truy_cap_bi_tu_choi, Language.khong_the_truy_cap_vao_thu_vien_anh, Language.dong);

                        return;
                    }

                    imageFile = await CrossMedia.Current.PickPhotoAsync();

                    if (imageFile != null)
                    {
                        ImageGoiVay.Source       = imageFile.Path;
                        BtnRemoveImage.IsVisible = true;
                        grImageGoiVay.IsVisible  = true;
                    }
                }
            }
        }