Example #1
0
        public IAsyncAction SetSourceAsync(IRandomAccessStream streamSource)
        {
            async Task SetSourceAsync(CancellationToken ct)
            {
                if (streamSource == null)
                {
                    //Same behavior as windows, although the documentation does not mention it!!!
                    throw new ArgumentException(nameof(streamSource));
                }

                PixelWidth  = 0;
                PixelHeight = 0;

#if __NETSTD__
                _stream = streamSource.CloneStream();

                var tcs = new TaskCompletionSource <object>();

                using var x = Subscribe(OnChanged);

                InvalidateSource();

                await tcs.Task;

                void OnChanged(ImageData data)
                {
                    tcs.TrySetResult(null);
                }
#else
                Stream = streamSource.CloneStream().AsStream();
#endif
            }

            return(AsyncAction.FromTask(SetSourceAsync));
        }
        private async void GetImage()
        {
            FileOpenPicker picker = new FileOpenPicker();

            picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            picker.FileTypeFilter.Add(".png");
            picker.FileTypeFilter.Add(".jpg");
            picker.FileTypeFilter.Add(".jpeg");

            StorageFile file = await picker.PickSingleFileAsync();

            if (file != null)
            {
                IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);

                BitmapImage image = new BitmapImage();
                await image.SetSourceAsync(stream.CloneStream());

                image.UriSource = new Uri(file.Path);

                MyBuffer buffer = new MyBuffer(new byte[stream.Size]);
                await stream.ReadAsync(buffer.Buffer, (uint)stream.Size, InputStreamOptions.None);

                var newAvatar = buffer.AsByteArray();

                Database_Service.SchedServiceClient client = new Database_Service.SchedServiceClient();
                account.avatarImage = newAvatar;
                Application.Current.Resources["User"] = account;
                await client.UpdateUserAsync(account.clientID, account.phoneNumber, account.address, account.username, newAvatar);

                EventViewModel e = this.DataContext as EventViewModel;
                e.newAvatar(newAvatar);
                DataContext = e;
            }
        }
        private Task <ShapefileRecordInfoCollection> BuildShapeIndexData(IRandomAccessStream stream, CancellationTokenSource cancellationTokenSource)
        {
            var token = cancellationTokenSource.Token;

            var task = Task.Factory.StartNew(
                async() =>
            {
                if (cancellationTokenSource.IsCancellationRequested)
                {
                    return(null);
                }

                using (var shapeStream = stream.CloneStream())
                {
                    int offset = 36;
                    shapeStream.Seek((ulong)offset);

                    byte[] boundingBox = new byte[32];
                    await shapeStream.ReadAsync(boundingBox.AsBuffer(), 32u, InputStreamOptions.Partial);

                    var recordInfos          = new ShapefileRecordInfoCollection();
                    recordInfos.BoundingRect = GetBoundingRect(boundingBox, this.CoordinateValueConverter);

                    offset = 100;
                    shapeStream.Seek((ulong)offset);

                    while (shapeStream.Position < shapeStream.Size)
                    {
                        if (cancellationTokenSource.IsCancellationRequested)
                        {
                            return(null);
                        }

                        byte[] recordHeader = new byte[8];
                        await shapeStream.ReadAsync(recordHeader.AsBuffer(), 8u, InputStreamOptions.Partial);

                        // The content length for a record is the length of the record contents section measured in 16-bit words.
                        int contentLength = ToInt32BigEndian(recordHeader, 4) * 2;

                        offset += 8;
                        recordInfos.Add(new ShapefileRecordInfo()
                        {
                            ContentOffset = offset, ContentLength = contentLength
                        });

                        offset += contentLength;
                        shapeStream.Seek((ulong)offset);
                    }

                    return(recordInfos);
                }
            },
                token).Unwrap();

            return(task);
        }
        public static async Task <Point> GetPixelWidthAndHeight(this IRandomAccessStream iRandomAccessStream)
        {
            var    tempIRandomAccessStream = iRandomAccessStream.CloneStream();
            Stream inputStream             = WindowsRuntimeStreamExtensions.AsStreamForRead(tempIRandomAccessStream.GetInputStreamAt(0));
            var    copiedBytes             = ConvertStreamTobyte(inputStream);
            Stream tempStream = new MemoryStream(copiedBytes);

            Guid      decoderId = Guid.Empty;
            ImageType type      = ImageTypeCheck.CheckImageType(copiedBytes);

            switch (type)
            {
            case ImageType.GIF:
            {
                break;
            }

            case ImageType.JPG:
            {
                decoderId = BitmapDecoder.JpegDecoderId;
                break;
            }

            case ImageType.PNG:
            {
                decoderId = BitmapDecoder.PngDecoderId;
                break;
            }

            default:
            {
                break;
            }
            }

            var randomAccessStream = new InMemoryRandomAccessStream();
            var outputStream       = randomAccessStream.GetOutputStreamAt(0);
            await RandomAccessStream.CopyAsync(tempStream.AsInputStream(), outputStream);

            var bitDecoder = await BitmapDecoder.CreateAsync(decoderId, randomAccessStream);

            var frame = await bitDecoder.GetFrameAsync(0);

            Point point = new Point();

            point.X = frame.PixelWidth;
            point.Y = frame.PixelHeight;
            return(point);
        }
Example #5
0
        private async void image_Tapped(object sender, TappedRoutedEventArgs e)
        {
            ;
            FileOpenPicker openPicker = new FileOpenPicker();

            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".png");

            StorageFile file = await openPicker.PickSingleFileAsync();

            if (file != null)
            {
                // Application now has read/write access to the picked file
                using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
                {
                    try
                    {
                        BitmapImage bitmapImage = new BitmapImage();
                        //   bitmapImage.DecodePixelWidth = 300;
                        await bitmapImage.SetSourceAsync(fileStream);

                        image.Source = bitmapImage;
                        // Set the image source to the selected bitmap
                        int x = int.Parse(await FileIO.ReadTextAsync(await ApplicationData.Current.LocalFolder.GetFileAsync("count.txt")));
                        Debug.WriteLine(x);
                        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream.CloneStream());

                        SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync();

                        StorageFile file_Save = await ApplicationData.Current.LocalFolder.CreateFileAsync(x.ToString() + ".png", CreationCollisionOption.ReplaceExisting);

                        x++;
                        await FileIO.WriteTextAsync(await ApplicationData.Current.LocalFolder.CreateFileAsync("count.txt", CreationCollisionOption.ReplaceExisting), x.ToString());

                        BitmapEncoder encoder = await BitmapEncoder.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.PngEncoderId, await file_Save.OpenAsync(FileAccessMode.ReadWrite));

                        encoder.SetSoftwareBitmap(softwareBitmap);
                        await encoder.FlushAsync();
                    }
                    catch { }
                }
            }
            else
            {
            }
        }
Example #6
0
        private static async Task <WriteableBitmap> ConvertStreamToWritableBitmap(Stream stream)
        {
            MemoryStream ms = new MemoryStream();

            stream.CopyTo(ms);
            IRandomAccessStream a1 = await ConvertToRandomAccessStream(ms);

            BitmapImage bitmapImage = new BitmapImage();
            await bitmapImage.SetSourceAsync(a1);

            WriteableBitmap writableBitmap = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
            await writableBitmap.SetSourceAsync(a1.CloneStream());

            return(writableBitmap);
        }
        public static async Task <IdentifiedFace> CheckGroupAsync(FaceServiceClient faceClient, Stream stream, string personGroupId, string groupImagesFolder)
        {
            try
            {
                var response = await FaceApiHelper.IdentifyPersonAsync(faceClient, stream, personGroupId);

                if (response?.Candidates == null || response.Candidates.Length == 0)
                {
                    return(null);
                }

                // Due to legal limitations, Face API does not support images retrieval in any circumstance currently.You need to store the images and maintain the relationship between face ids and images by yourself.
                var personsFolder = await PicturesHelper.GetPersonFolderAsync(groupImagesFolder);

                var dataSet = await faceClient.ListPersonsAsync(personGroupId);

                var matches =
                    from c in response.Candidates
                    join p in dataSet on c.PersonId equals p.PersonId into ps
                    from p in ps.DefaultIfEmpty()
                    select new IdentifiedFace
                {
                    Confidence = c.Confidence,
                    PersonName = p == null ? "(No matching face)" : p.Name,
                    FaceId     = c.PersonId
                };

                var match = matches.OrderByDescending(m => m.Confidence).FirstOrDefault();


                if (match == null)
                {
                    return(null);
                }

                var matchFile = await personsFolder.GetFileAsync($"{match.PersonName}.{Constants.LocalPersonFileExtension}");

                IRandomAccessStream photoStream = await matchFile.OpenReadAsync();

                match.FaceStream = photoStream.CloneStream().AsStream();
                return(match);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Example #8
0
        private async void OnCaptured(IRandomAccessStream stream)
        {
            SendImage(stream);

            using (var streamClone = stream.CloneStream())
            {
                BitmapImage bitmap = new BitmapImage();

                await bitmap.SetSourceAsync(streamClone);

                this.CaptureImage                 = bitmap;
                this.CaptureImageVisibility       = Visibility.Visible;
                App.Locator.Complete.CaptureImage = bitmap;
            }

            this.IsCapture = false;
        }
Example #9
0
        public static async Task Save(IRandomAccessStream messageStream, string fileName)
        {
            IRandomAccessStream audioStream   = messageStream.CloneStream();
            StorageFolder       storageFolder = KnownFolders.MusicLibrary;
            StorageFile         storageFile   = await storageFolder.CreateFileAsync(
                fileName, CreationCollisionOption.ReplaceExisting);

            using (IRandomAccessStream fileStream =
                       await storageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                await RandomAccessStream.CopyAndCloseAsync(
                    audioStream.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));

                await audioStream.FlushAsync();

                audioStream.Dispose();
            }
        }
Example #10
0
        private async void ELPSaudio_PointerReleased(object sender, PointerRoutedEventArgs e)
        {
            lock (o)
            {
                recording = false;
            }
            GRIDrecord.Opacity = 1;
            STRBDrecord.Stop();
            SCALEaudio.ScaleX = SCALEaudio.ScaleY = 1;
            try
            {
                audioStream = await recorder.StopRecording();

                APaudio.SetSource(audioStream.CloneStream());
                //Length = APaudio.TotalLength;
            }catch {
                Constants.BoxPage.ShowMessage("录制失效!");
            }
        }
Example #11
0
        private void SetSourceCore(IRandomAccessStream streamSource)
        {
            if (streamSource == null)
            {
                //Same behavior as windows, although the documentation does not mention it!!!
                throw new ArgumentException(nameof(streamSource));
            }

            PixelWidth  = 0;
            PixelHeight = 0;

            // The source has to be cloned before leaving the "SetSource[Async]".
            var clonedStreamSource = streamSource.CloneStream();

#if __NETSTD__
            _stream = clonedStreamSource;
#else
            Stream = clonedStreamSource.AsStream();
#endif
        }
        private async Task EvaluateFromImageAsync(IRandomAccessStream stream)
        {
            var result = await _model.EvaluateModelAsync(stream.CloneStream());

            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                try
                {
                    //handle object detection on UI thread
                    var highestProbability = result.Loss.Where(l => l.Value > 0.65f).ToList();
                    outputLabel.Text       = highestProbability.Count > 0 ? highestProbability.FirstOrDefault().Key : "No result";

                    var label             = $"Evaluation Time: {result.EvaluationTimeMilliseconds}ms\r\n";
                    label                += string.Join("\r\n", result.Loss.Select(l => l.Key + ": " + l.Value));
                    outputDebugLabel.Text = label;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
            });
        }
        private async void pictureButton_Tapped(object sender, TappedRoutedEventArgs e)
        {
            try
            {
                CameraCaptureUI captureUI = new CameraCaptureUI();
                captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;

                StorageFile photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);

                IRandomAccessStream imageStream;
                using (IRandomAccessStream fileStream = await photo.OpenAsync(FileAccessMode.Read))
                {
                    imageStream = fileStream.CloneStream();
                }

                petImage = await ConvertToArray(imageStream);
            }

            catch (Exception)
            {
            }
        }
Example #14
0
        private async void PlayBeep(String fileName)
        {
            //ms-appx:///Assets/media/beep-06.wav
            await Page2Dispatcher.RunAsync(CoreDispatcherPriority.Low, async() =>
            {
                MediaElement playbackMediaElement = new MediaElement();
                StorageFolder appInstalledFolder  = Windows.ApplicationModel.Package.Current.InstalledLocation;
                StorageFolder assets    = await appInstalledFolder.GetFolderAsync("Assets\\media");
                var files               = await assets.GetFilesAsync();
                StorageFile storageFile = files.FirstOrDefault(a => a.Name == fileName);

                //foreach (StorageFile storageFile in files)
                {
                    using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.Read))
                    {
                        /// IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read);
                        playbackMediaElement.SetSource(fileStream.CloneStream(), storageFile.FileType);
                        playbackMediaElement.Play();
                    }
                }
            });
        }
        public async void saveFile()
        {
            imageFileName    = "apereImage7" + imageFileNumber + ".jpg";
            imageFileNumber += 1;

            //Save: Start by copying the stream and loading it into a decoder
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream.CloneStream());

            SoftwareBitmap softBitmap = await decoder.GetSoftwareBitmapAsync();

            //To actually save, we need to encode it. This first line creates a file with name image1.jpg and replaces the image if it exists
            StorageFile saveFile = await local.CreateFileAsync(imageFileName, CreationCollisionOption.ReplaceExisting);

            //Bitmap encoder encode in jpeg, specify it to the stream above "saveFile" openasync allows me to write to this stream
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.JpegEncoderId, await saveFile.OpenAsync(FileAccessMode.ReadWrite));

            encoder.SetSoftwareBitmap(softBitmap);
            await encoder.FlushAsync();

            FileInfo f = new FileInfo(imageFileName);

            path = f.FullName;
            System.Diagnostics.Debug.WriteLine(f.FullName);
        }
Example #16
0
 public IRandomAccessStream CloneStream() => imrac.CloneStream();
Example #17
0
 public IRandomAccessStream CloneStream() => new SegmentRandomAccessStream(Stream.CloneStream(), Offset, Length);
Example #18
0
 public Subscriber()
 {
     //the two streams actually point to the same underlying data 
     _incomingStream = new InMemoryRandomAccessStream();
     _playingStream = _incomingStream.CloneStream();
 }
        private static Task <DbfHeader> BuildDbfHeaderData(IRandomAccessStream stream, Encoding encoding, CancellationTokenSource cancellationTokenSource)
        {
            var token = cancellationTokenSource.Token;

            var task = Task.Factory.StartNew(async() =>
            {
                if (cancellationTokenSource.IsCancellationRequested)
                {
                    return(null);
                }

                if (stream.Size < 32)
                {
                    throw new NotSupportedException(InvalidFormat);
                }

                using (var dataStream = stream.CloneStream())
                {
                    byte[] header = new byte[32];
                    await dataStream.ReadAsync(header.AsBuffer(), 32u, InputStreamOptions.Partial);

                    byte fileType = header[0];
                    if (!AllowedTypes.Contains(fileType))
                    {
                        throw new NotSupportedException(InvalidFormat);
                    }

                    DbfHeader dbfHeader     = new DbfHeader();
                    dbfHeader.RecordsCount  = BitConverter.ToInt32(header, 4);
                    dbfHeader.RecordsOffset = BitConverter.ToInt16(header, 8);
                    dbfHeader.RecordLength  = BitConverter.ToInt16(header, 10);

                    if (encoding == null)
                    {
                        byte languageDriver = header[29];
                        encoding            = DbfEncoding.GetEncoding(languageDriver);
                    }

                    dbfHeader.Encoding = encoding;

                    // header is 32 bytes + n field descriptors * 32 bytes + carriage return byte (0x0D)
                    int fieldDescriptorCount = (dbfHeader.RecordsOffset - 32 - 1) / 32;
                    byte[] fieldDescriptor;
                    DbfFieldInfo dbfField;
                    for (int i = 0; i < fieldDescriptorCount; i++)
                    {
                        if (cancellationTokenSource.IsCancellationRequested)
                        {
                            return(null);
                        }

                        fieldDescriptor = new byte[32];
                        await dataStream.ReadAsync(fieldDescriptor.AsBuffer(), 32u, InputStreamOptions.Partial);

                        dbfField               = new DbfFieldInfo();
                        dbfField.Name          = encoding.GetString(fieldDescriptor, 0, 11).Replace("\0", string.Empty);
                        dbfField.NativeDbfType = (char)fieldDescriptor[11];

                        dbfField.Length       = fieldDescriptor[16];
                        dbfField.DecimalCount = fieldDescriptor[17];

                        dbfHeader.Fields.Add(dbfField);
                    }

                    return(dbfHeader);
                }
            },
                                             token).Unwrap();

            return(task);
        }
 private void appBarMenuItem_Click(object sender, EventArgs e)
 {
     myService.State["action"] = "Send_Audio";
     _randomAccessStream.CloneStream();
     NavigationService.GoBack();
 }
Example #21
0
File: Print3D.cs Project: ice0/test
 public IRandomAccessStream CloneStream()
 {
     return(_stream.CloneStream());
 }
Example #22
0
 public Subscriber()
 {
     //the two streams actually point to the same underlying data
     _incomingStream = new InMemoryRandomAccessStream();
     _playingStream  = _incomingStream.CloneStream();
 }
Example #23
0
 public IRandomAccessStream CloneStream()
 {
     return(imrac.CloneStream());
 }
Example #24
0
 public Stream GetSource() => stream.CloneStream().AsStream();
Example #25
0
 public IRandomAccessStream CloneStream()
 => _stream.CloneStream();