Esempio n. 1
0
        // Load the image as a stream
        public async Task LoadPhotoAsync(FileResult photo)
        {
            try
            {
                if (photo == null)
                {
                    PhotoPath = null;
                    return;
                }

                // save the file into local storage
                var newFile = Path.Combine(FileSystem.CacheDirectory, photo.FileName);
                using (var stream = await photo.OpenReadAsync())
                    using (var newStream = File.OpenWrite(newFile))
                        await stream.CopyToAsync(newStream);

                var streamImage = await photo.OpenReadAsync();

                // resultImage.Source = ImageSource.FromStream(() => streamImage);

                PhotoPath = newFile;
            }
            catch (Exception ex)
            {
                throw new CameraException(ex.ToString());
            }
        }
Esempio n. 2
0
        public async static Task <HandGesturePrediction> Classify(FileResult file)
        {
            using (var image = await file.OpenReadAsync())
            {
                HttpContent fileStreamContent = new StreamContent(image);

                var fn = $"{Guid.NewGuid()}.jpeg";

                fileStreamContent.Headers.ContentDisposition =
                    new ContentDispositionHeaderValue("form-data")
                {
                    Name = "file", FileName = fn
                };

                fileStreamContent.Headers.ContentType =
                    new MediaTypeHeaderValue("application/octet-stream");

                using (var formData = new MultipartFormDataContent())
                {
                    formData.Add(fileStreamContent);
                    var response = await client.PostAsync(classifyApi, formData);

                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();

                        var mlGesture = JsonConvert.DeserializeObject <HandGesturePrediction>(json);
                        return(mlGesture);
                    }
                }
            }

            return(new HandGesturePrediction());
        }
Esempio n. 3
0
        public static async Task <FileInfo> LoadPhotoAsync(this FileResult photo)
        {
            await Task.Yield();

            // canceled
            if (photo == null)
            {
                return(null);
            }
            // save the file into local storage
            DirectoryInfo tmpDir = new DirectoryInfo(Tools.Instance.TemporalPath);

            if (!tmpDir.Exists)
            {
                tmpDir.Create();
            }
            string   newFile = Path.Combine(tmpDir.FullName, photo.FileName);
            FileInfo file    = new FileInfo(newFile);

            if (Tools.Instance.RuntimePlatform == RuntimePlatform.iOS && file.Exists)
            {
                return(file);
            }
            using (Stream stream = await photo.OpenReadAsync())
            {
                using (FileStream newStream = new FileStream(file.FullName, FileMode.OpenOrCreate))
                {
                    await stream.CopyToAsync(newStream);
                }
            }

            file.Refresh();
            return(file);
        }
        private async void ButtonUploadFile_Clicked(object sender, EventArgs e)
        {
            try
            {
                if (_selectedFile == null)
                {
                    return;
                }

                ActivityIndicator.IsRunning = true;

                var content = new MultipartFormDataContent();
                content.Add(new StreamContent(await _selectedFile.OpenReadAsync()), "photo", _selectedFile.FileName);

                var httpClient = new HttpClient();
                var response   = await httpClient.PostAsync("http://192.168.86.25:5000/FileUpload", content);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    LabelFileName.Text         = $"{_selectedFile.FileName} upload success.";
                    ButtonUploadFile.IsEnabled = false;
                }
                else
                {
                    LabelFileName.Text = $"{_selectedFile.FileName} upload failed.";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Ops something went wrong: {ex.Message}");
                LabelFileName.Text = $"{_selectedFile.FileName} upload failed.";
            }

            ActivityIndicator.IsRunning = false;
        }
Esempio n. 5
0
        public static async Task <string> EmbedMedia(FileResult result, bool isPhoto)
        {
            //checks if result is existent file or just captrued and decides if to store it in system gallery
            if (result != null)
            {
                string fullPath = string.Empty;

                //check if it needs to be saved first
                if (result.FullPath.Contains("com.companyname.TestZXing"))
                {
                    //save
                    fullPath = await Functions.SaveToGallery(result, isPhoto);
                }
                else
                {
                    fullPath = result.FullPath;
                }

                var stream = await result.OpenReadAsync();

                return(fullPath); //ImageSource.FromStream(() => stream);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 6
0
        private async void OpenButton_Clicked(object sender, EventArgs e)
        {
            FileResult picked = null;

            try
            {
                picked = await FilePicker.PickAsync(new PickOptions
                {
                    PickerTitle = "Select JCF archive",
                    FileTypes   = new FilePickerFileType(new Dictionary <DevicePlatform, IEnumerable <string> >
                    {
                        { DevicePlatform.Android, new[] { "application/zip" } },
                        { DevicePlatform.iOS, new[] { "com.pkware.zip-archive" } },
                        { DevicePlatform.macOS, new[] { "com.pkware.zip-archive", "zip" } },
                        { DevicePlatform.UWP, new[] { ".zip" } },
                        { DevicePlatform.Unknown, new[] { ".zip" } }
                    })
                });

                if (picked == null)
                {
                    return;
                }

                var song = App.Library.AddSong(await picked.OpenReadAsync());

                await DisplayAlert(Localized.MenuPage_Import, song.ToString(), "OK");
            }
            catch (Exception)
            {
                var path = picked == null ? string.Empty : picked.FullPath;
                await DisplayAlert(Localized.MenuPage_ImportCatchTitle, string.Format(Localized.MenuPage_ImportCatch, path), "OK");
            }
        }
Esempio n. 7
0
        // Helper function to set the photo in both taking a picture or picking one from the library.
        async void SetPhoto(FileResult photo)
        {
            if (photo == null)
            {
                await Shell.Current.DisplayAlert("NO PHOTO", "Something went wrong with grabbing the photo to use.", "OK");

                return;
            }

            rawImage = photo;

            // Get file stream and set it as photo.
            var newFile = Path.Combine(FileSystem.CacheDirectory, rawImage.FileName);

            Debug.WriteLine(newFile);

            using (var stream = await photo.OpenReadAsync())
            {
                using (var newStream = File.OpenWrite(newFile))
                {
                    await stream.CopyToAsync(newStream);
                }
                SelectedImage = ImageSource.FromFile(newFile);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Load Photo
        /// </summary>
        /// <param name="photo"></param>
        /// <returns></returns>
        public async Task <PhotoItemModel> LoadPhotoAsync(FileResult photo)
        {
            if (photo == null)
            {
                return(null);
            }

            var base64String = string.Empty;
            // save the file into local storage
            var fullPath = Path.Combine(FileSystem.CacheDirectory, photo.FileName);

            using (var stream = await photo.OpenReadAsync().ConfigureAwait(false))
            {
                using (var writeStream = File.OpenWrite(fullPath))
                    await stream.CopyToAsync(writeStream).ConfigureAwait(false);

                using (var readStream = File.OpenRead(fullPath))
                {
                    var stringBytes = MethodHelper.ReadAllBytes(readStream);
                    base64String = Convert.ToBase64String(stringBytes);
                }
            }

            var compressedBase64 = MethodHelper.Compress(base64String);

            return(new PhotoItemModel()
            {
                FullPath = fullPath,
                PhotoFileName = photo.FileName,
                Description = photo.ContentType,
                Base64String = base64String,
                CompressedBase64String = compressedBase64
            });
        }
Esempio n. 9
0
        //Set the feed icon
        private async void btn_SetIcon_Clicked(object sender, EventArgs e)
        {
            try
            {
                Feeds SelectedItem = (Feeds)listview_Items.SelectedItem;
                if (SelectedItem != null)
                {
                    List <string> messageAnswers = new List <string>();
                    messageAnswers.Add("Set custom icon");
                    messageAnswers.Add("Reset the icon");
                    messageAnswers.Add("Cancel");

                    string messageResult = await MessagePopup.Popup("Change the feed icon", "Would you like to set a custom feed icon for " + SelectedItem.feed_title + "?", messageAnswers);

                    if (messageResult == "Set custom icon")
                    {
                        Debug.WriteLine("Changing icon for feed: " + SelectedItem.feed_id + " / " + SelectedItem.feed_title);

                        PickOptions pickOptions = new PickOptions();
                        pickOptions.FileTypes = FilePickerFileType.Png;

                        FileResult pickResult = await FilePicker.PickAsync(pickOptions);

                        if (pickResult != null)
                        {
                            //Load feed icon
                            Stream imageStream = await pickResult.OpenReadAsync();

                            //Update feed icon
                            if (imageStream.CanSeek)
                            {
                                imageStream.Position = 0;
                            }
                            SelectedItem.feed_icon = ImageSource.FromStream(() => imageStream);

                            //Save feed icon
                            AVFiles.File_SaveStream(SelectedItem.feed_id + ".png", imageStream, true, true);
                        }
                    }
                    else if (messageResult == "Reset the icon")
                    {
                        //Delete the feed icon
                        AVFiles.File_Delete(SelectedItem.feed_id + ".png", true);

                        //Load default feed icon
                        SelectedItem.feed_icon = ImageSource.FromResource("NewsScroll.Assets.iconRSS-Dark.png");

                        //Reset the online status
                        OnlineUpdateFeeds = true;
                        ApiMessageError   = string.Empty;

                        List <string> messageAnswersReset = new List <string>();
                        messageAnswersReset.Add("Ok");

                        await MessagePopup.Popup("Feed icon reset", "The feed icon has been reset and will be refreshed on the next online feed update, you can refresh the feeds by clicking on the refresh icon above.", messageAnswersReset);
                    }
                }
            }
            catch { }
        }
Esempio n. 10
0
        private async void Upload(FileResult file)
        {
            try
            {
                using (Busy())
                {
                    using (var stream = await file.OpenReadAsync())
                    {
                        using (var client = new HttpClient())
                            using (var formData = new MultipartFormDataContent())
                            {
                                formData.Add(new StreamContent(stream), "file1", file.FileName);

                                formData.Headers.TryAddWithoutValidation("session-handle", (await SessionHandler.Session.Ping()).Handle);

                                var response = await client.PostAsync(new Uri(SessionHandler.Session.Configuration.Uri(), "/majaocr"), formData);

                                response.EnsureSuccessStatusCode();
                                var id = await response.Content.ReadAsStringAsync();

                                await SessionHandler.ExecuteOpenbiCommand((s, t) => s.AnalyzeOcrDocument(id));

                                FileUploaded?.Invoke(this, new StringEventArgs(id));
                            }
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayException(ex);
            }
        }
Esempio n. 11
0
        public async Task EmbedMedia(FileResult result, bool isPhoto)
        {
            if (result != null)
            {
                string fullPath = string.Empty;

                //check if it needs to be saved first
                if (result.FullPath.Contains("com.companyname.TestZXing"))
                {
                    //save
                    fullPath = await Functions.SaveToGallery(result, isPhoto);
                }
                else
                {
                    fullPath = result.FullPath;
                }

                var stream = await result.OpenReadAsync();

                ActiveElementPath = ImageSource.FromStream(() => stream);
                Items.Add(new File
                {
                    Name        = result.FileName,
                    Link        = fullPath,
                    ImageSource = fullPath
                });
            }
        }
Esempio n. 12
0
        async Task LoadPhotoAsync(FileResult photo)
        {
            // canceled
            if (photo == null)
            {
                FilePath = "";
                return;
            }
            // save the file into local storage
            var newFile = Path.Combine(FileSystem.CacheDirectory, "MyPhoto.png");

            using (var stream = await photo.OpenReadAsync())
                using (var newStream = File.OpenWrite(newFile))
                    await stream.CopyToAsync(newStream);

            File.Delete(photo.FullPath);
            FilePath = newFile;

            FileResult showFile = new FileResult(FilePath);

            Photo = ImageSource.FromStream(() =>
            {
                Stream stream = showFile.OpenReadAsync().Result;
                return(stream);
            });
        }
Esempio n. 13
0
        public static async Task <string> SaveNewPhoto(FileResult photo)
        {
            //Save in {App Directory}\img\{GUID}.jpg
            string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "img", Guid.NewGuid().ToString() + ".jpg");

            //Canceled
            if (photo == null)
            {
                return(null);
            }

            //Create img folder if needed
            if (!Directory.Exists(Path.GetDirectoryName(path)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(path));
            }

            //Save the file to folder
            using (Stream stream = await photo.OpenReadAsync())
                using (Bitmap b = (Bitmap)ShimDrawing::System.Drawing.Image.FromStream(stream))
                    using (Stream img = File.OpenWrite(path))
                    {
                        FiltersSequence f = new FiltersSequence();
                        f.Add(new ResizeBilinear(800, (int)(800.0 * b.Height / b.Width)));

                        if (b.Height < b.Width)
                        {
                            f.Add(new RotateBilinear(-90));
                        }

                        f.Apply(ImageProcessor.Format(b)).Save(img, ShimDrawing::System.Drawing.Imaging.ImageFormat.Jpeg);
                    }

            return(path);
        }
Esempio n. 14
0
        public static async Task <string> SaveToGallery(FileResult result, bool isPhoto)
        {
            //takes care of storing photo/video taken with camera in system gallery
            string mPath = string.Empty;

            if (isPhoto)
            {
                mPath = DependencyService.Get <IFileHandler>().GetImageGalleryPath();
            }
            else
            {
                mPath = DependencyService.Get <IFileHandler>().GetVideoGalleryPath();
            }

            string nPath = System.IO.Path.Combine(mPath, result.FileName);

            using (var stream = await result.OpenReadAsync())
            {
                using (var nStream = System.IO.File.OpenWrite(nPath))
                {
                    await stream.CopyToAsync(nStream);

                    return(nPath);
                }
            }
        }
Esempio n. 15
0
        // save the photo into local storage
        private async Task loadPhotoAsync(FileResult photo)
        {
            // create file path
            var newFile = Path.Combine(galleryPath, photo.FileName);

            // read the photo
            using (var stream = await photo.OpenReadAsync())
                using (var newStream = File.OpenWrite(newFile))
                    await stream.CopyToAsync(newStream); // save the photo
        }
Esempio n. 16
0
        private async void OnSaveBtnClicked(object sender, EventArgs e)
        {
            if (_photo != null)
            {
                // save the file into 'Camera Roll'
                var stream = await _photo.OpenReadAsync();

                DependencyService.Get <ISaveImage>().SaveImageToCameraRoll(stream);
            }
            SaveBtn.IsEnabled = false;
        }
Esempio n. 17
0
        private async Task <Stream> GetBytesFromPhotoAsync(FileResult fileResult)
        {
            Stream newStream = null;


            var newFile = Path.Combine(FileSystem.CacheDirectory, fileResult.FileName);

            using (var stream = await fileResult.OpenReadAsync())
                using (newStream = File.OpenWrite(newFile))
                    await stream.CopyToAsync(newStream);

            return(File.OpenRead(newFile));
        }
Esempio n. 18
0
        // asks the user to choose a file, asynchronously
        public async Task <OpenedFile> PromptUserForFile()
        {
            await this.requestPermission();

            ;
            FileResult fileData = await FilePicker.PickAsync();

            if (fileData == null)
            {
                return(null);
            }
            return(new OpenedFile(fileData.FullPath, await fileData.OpenReadAsync()));
        }
Esempio n. 19
0
        public async Task <string> Edit(string attachmentPath)
        {
            string _Result = "OK";

            if (string.IsNullOrEmpty(attachmentPath))
            {
                //_Result = await Edit();
            }
            else
            {
                if (!System.IO.File.Exists(attachmentPath))
                {
                    _Result = $"Plik w lokacji {attachmentPath} nie istnieje lub program nie ma uprawnień dostępu do tej lokacji..";
                }
                else
                {
                    try
                    {
                        var        serialized = JsonConvert.SerializeObject(this);
                        string     url        = Secrets.ApiAddress + $"Edit{typeof(T).Name}?token=" + Secrets.TenantToken + $"&id={this.Id}&UserId={RuntimeSettings.CurrentUser.UserId}&{typeof(T).Name}Json={serialized}";
                        HttpClient httpClient = new HttpClient(new NativeMessageHandler()
                        {
                            Timeout = new TimeSpan(0, 0, 20), EnableUntrustedCertificates = true, DisableCaching = true
                        });
                        var           content = new MultipartFormDataContent();
                        var           file    = new FileResult(attachmentPath);
                        StreamContent img     = new StreamContent(await file.OpenReadAsync());
                        img.Headers.Add("Content-Type", file.ContentType);
                        content.Add(img, "file", file.FileName);
                        HttpResponseMessage result = await Static.Functions.GetPostRetryAsync(() => httpClient.PutAsync(new Uri(url), content), TimeSpan.FromSeconds(3));

                        if (!result.IsSuccessStatusCode)
                        {
                            IsSaved = false; //hasn't been saved
                            _Result = result.ReasonPhrase;
                        }
                        else
                        {
                            IsSaved = true;//has been saved successfully
                        }
                    }
                    catch (Exception ex)
                    {
                        _Result = ex.Message;
                        Static.Functions.CreateError(ex, "No connection", nameof(this.Edit), this.GetType().Name);
                    }
                }
            }

            return(_Result);
        }
Esempio n. 20
0
        public async Task <string> UploadVideo(FileResult video)
        {
            Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.Instance;
            var stream = await video.OpenReadAsync();

            var name = System.Guid.NewGuid() + ".mp4";
            await storage.GetReference(name).PutStream(stream);

            stream.Close();

            var url = await storage.GetReference(name).GetDownloadUrl();

            return(url.ToString());
        }
Esempio n. 21
0
        async Task LoadPhotoAsync(FileResult photo)
        {
            // canceled
            if (photo == null)
            {
                return;
            }
            // save the file into local storage
            var newFile = Path.Combine(FileSystem.CacheDirectory, photo.FileName);

            using (var stream = await photo.OpenReadAsync())
                using (var newStream = File.OpenWrite(newFile))
                    await stream.CopyToAsync(newStream);
        }
Esempio n. 22
0
        private async void OnCameraBtnClicked(object sender, EventArgs e)
        {
            _photo = await MediaPicker.CapturePhotoAsync();

            if (_photo != null)
            {
                var stream = await _photo.OpenReadAsync();

                PhotoImage.Source = ImageSource.FromStream(() =>
                {
                    return(stream);
                });
            }
            SaveBtn.IsEnabled = true;
        }
Esempio n. 23
0
        async Task LoadPhotoAsync(FileResult photo)
        {
            if (photo == null)
            {
                PhotoPath = null;
                return;
            }

            var newFile = Path.Combine(FileSystem.CacheDirectory, photo.FileName);

            using (var stream = await photo.OpenReadAsync())
                using (var newStream = File.OpenWrite(newFile))
                    await stream.CopyToAsync(newStream);

            PhotoPath = newFile;
        }
Esempio n. 24
0
        public async Task <SpixiImageData> PickFileAsync()
        {
            FileResult fileData = await FilePicker.PickAsync();

            if (fileData == null)
            {
                return(null); // User canceled file picking
            }
            SpixiImageData spixi_img_data = new SpixiImageData()
            {
                name = fileData.FileName, path = fileData.FullPath, stream = await fileData.OpenReadAsync()
            };

            // Return Task object
            return(spixi_img_data);
        }
        /// <summary>
        /// save image to local storage and return path of the image
        /// </summary>
        private async Task SaveAndReturn(FileResult photo)
        {
            //save to local storage
            var newFile = Path.Combine(FileSystem.AppDataDirectory, photo.FileName);

            using (var stream = await photo.OpenReadAsync())
                using (var newStream = File.OpenWrite(newFile))
                    await stream.CopyToAsync(newStream);

            //return image path
            var dialog_params = new DialogParameters {
                { "ImagePath", photo.FullPath }
            };

            RequestClose?.Invoke(dialog_params);
        }
Esempio n. 26
0
        private static async Task <string> SavePhoto(FileResult file)
        {
            if (file == null)
            {
                return(string.Empty);
            }

            var fileName = file.FileName;
            var folder   = FileSystem.AppDataDirectory;
            var newFile  = Path.Combine(folder, fileName);

            using (var stream = await file.OpenReadAsync())
                using (var newStream = File.OpenWrite(newFile))
                    await stream.CopyToAsync(newStream);

            return(newFile);
        }
Esempio n. 27
0
        /// <summary>
        /// Gets the CurrentDataFolder folder
        /// </summary>
        /// <returns>
        /// True if a file was picked. False if not.
        /// </returns>
        public static async Task <bool> PickCurrentInputFile()
        {
            try
            {
                FilePickerFileType customFileType =
                    new FilePickerFileType(
                        new Dictionary <DevicePlatform,
                                        IEnumerable <string> >
                {
                    //{ DevicePlatform.iOS, new[] { "public.my.comic.extension" } }, // TODO add these or general UTType values
                    { DevicePlatform.Android, new[] { "application/octet-stream" } },
                    { DevicePlatform.UWP, new[] { ".gpkg", ".gramps" } },
                    //{ DevicePlatform.macOS, new[] { "cbr" } }, // TODO add these or general UTType values
                }
                        );

                var options = new PickOptions
                {
                    PickerTitle = "Please select a Gramps input file",
                    FileTypes   = customFileType,
                };

                FileResult result = await FilePicker.PickAsync(options);

                if (result == null)
                {
                    return(false); // user canceled file picking
                }

                Debug.WriteLine("Picked file name is: " + result.FileName);

                DataStore.Instance.AD.CurrentInputStream = await result.OpenReadAsync();

                DataStore.Instance.AD.CurrentInputStreamPath = result.FullPath;
            }

            // TODO fix this. Fail and force reload next time.
            catch (Exception ex)
            {
                App.Current.Services.GetService <IErrorNotifications>().NotifyException("Exception in PickCurrentInputFile", ex);

                throw;
            }

            return(true);
        }
Esempio n. 28
0
        async Task <Android.Net.Uri[]> LoadPhotoAsync(FileResult photo)
        {
            // cancelled
            if (photo == null)
            {
                _photoPath = null;
                return(null);
            }
            // save the file into local storage
            var newFile = Path.Combine(FileSystem.CacheDirectory, photo.FileName);

            using (var stream = await photo.OpenReadAsync())
                using (var newStream = File.OpenWrite(newFile))
                    await stream.CopyToAsync(newStream);
            _photoPath = newFile;
            Android.Net.Uri uri = Android.Net.Uri.FromFile(new Java.IO.File(_photoPath));
            return(new Android.Net.Uri[] { uri });
        }
        async Task LoadVideoAsync(FileResult video)
        {
            //canceled
            if (video == null)
            {
                VideoPath = null;
                return;
            }

            //save the file into local storage
            var newFile = Path.Combine(FileSystem.CacheDirectory, video.FileName);

            using (var stream = await video.OpenReadAsync())
                using (var newStream = File.OpenWrite(newFile))
                    await stream.CopyToAsync(newStream);

            VideoPath = newFile;
        }
Esempio n. 30
0
        async Task LoadPhotoAsync(FileResult photo)
        {  // https://docs.microsoft.com/en-us/xamarin/essentials/media-picker?tabs=android
           // save Picture taken...
            // canceled
            if (photo == null)
            {
                PhotoPath = null;
                return;
            }
            // save the file into local storage
            var newFile = Path.Combine(FileSystem.CacheDirectory, photo.FileName);

            using (var stream = await photo.OpenReadAsync())
                using (var newStream = File.OpenWrite(newFile))
                    await stream.CopyToAsync(newStream);

            PhotoPath = newFile;
        }