Ejemplo n.º 1
0
        public static async Task <IRandomAccessStream> ImageToJPegStreamAsync(IRandomAccessStream imageStream)
        {
            //Create a decoder for the image
            var decoder = await BitmapDecoder.CreateAsync(imageStream);

            PixelDataProvider pixelData = await decoder.GetPixelDataAsync();

            byte[] pixelBytes = pixelData.DetachPixelData();

            //
            InMemoryRandomAccessStream jpegStream = new InMemoryRandomAccessStream();

            double jpegImageQuality = 0.9;

            var propertySet  = new BitmapPropertySet();
            var qualityValue = new BitmapTypedValue(jpegImageQuality, Windows.Foundation.PropertyType.Single);

            propertySet.Add("ImageQuality", qualityValue);

            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, jpegStream, propertySet);

            //key thing here is to use decoder.OrientedPixelWidth and decoder.OrientedPixelHeight otherwise you will get garbled image on devices on some photos with orientation in metadata
            encoder.SetPixelData(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, decoder.OrientedPixelWidth, decoder.OrientedPixelHeight, decoder.DpiX, decoder.DpiY, pixelBytes);

            //ulong jpegImageSize = 0;
            //jpegImageSize = jpegStream.Size;

            await encoder.FlushAsync();

            await jpegStream.FlushAsync();

            return(jpegStream);
        }
Ejemplo n.º 2
0
        private async Task <byte[]> ImageToBytes(IRandomAccessStream sourceStream)
        {
            byte[] imageArray;

            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);

            var transform = new BitmapTransform {
                ScaledWidth = decoder.PixelWidth, ScaledHeight = decoder.PixelHeight
            };
            PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                BitmapPixelFormat.Rgba8,
                BitmapAlphaMode.Straight,
                transform,
                ExifOrientationMode.RespectExifOrientation,
                ColorManagementMode.DoNotColorManage);

            using (var destinationStream = new InMemoryRandomAccessStream())
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destinationStream);

                encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, decoder.PixelWidth,
                                     decoder.PixelHeight, 96, 96, pixelData.DetachPixelData());
                await encoder.FlushAsync();

                BitmapDecoder outputDecoder = await BitmapDecoder.CreateAsync(destinationStream);

                await destinationStream.FlushAsync();

                imageArray = (await outputDecoder.GetPixelDataAsync()).DetachPixelData();
            }
            return(imageArray);
        }
Ejemplo n.º 3
0
        private async Task SetTileImageAsync(Tile tile, IBuffer buffer)
        {
            var tcs = new TaskCompletionSource <object>();

            using (var stream = new InMemoryRandomAccessStream())
            {
                await stream.WriteAsync(buffer);

                await stream.FlushAsync(); // necessary?

                stream.Seek(0);

                await tile.Image.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                {
                    try
                    {
                        var bitmapImage = new BitmapImage();
                        await bitmapImage.SetSourceAsync(stream);

                        tile.SetImage(bitmapImage);
                        tcs.SetResult(null);
                    }
                    catch (Exception ex)
                    {
                        tcs.SetException(ex);
                    }
                });
            }

            await tcs.Task;
        }
Ejemplo n.º 4
0
        private async Task <Result> GetCameraImage(CancellationToken cancelToken)
        {
            if (cancelToken.IsCancellationRequested)
            {
                throw new OperationCanceledException(cancelToken);
            }

            imageStream = new InMemoryRandomAccessStream();

            await capture.CapturePhotoToStreamAsync(encodingProps, imageStream);

            await imageStream.FlushAsync();

            var decoder = await BitmapDecoder.CreateAsync(imageStream);

            byte[] pixels =
                (await
                 decoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8,
                                           BitmapAlphaMode.Ignore,
                                           new BitmapTransform(),
                                           ExifOrientationMode.IgnoreExifOrientation,
                                           ColorManagementMode.DoNotColorManage)).DetachPixelData();

            const BitmapFormat format = BitmapFormat.RGB32;

            imageStream.Dispose();

            var result =
                await
                Task.Run(
                    () => barcodeReader.Decode(pixels, (int)decoder.PixelWidth, (int)decoder.PixelHeight, format),
                    cancelToken);

            return(result);
        }
Ejemplo n.º 5
0
        private async Task TakePhoto()
        {
            // Set properties of image(jpeg) and Capture a image into a new stream
            ImageEncodingProperties properties = ImageEncodingProperties.CreateJpeg();

            using (IRandomAccessStream ras = new InMemoryRandomAccessStream())
            {
                await this.capture.CapturePhotoToStreamAsync(properties, ras);

                await ras.FlushAsync();

                // Load the image into a BitmapImage set stream to 0 for next photo
                ras.Seek(0);
                var picLocation = new BitmapImage();
                picLocation.SetSource(ras);

                //place into listview
                var img = new Image()
                {
                    Width = 200, Height = 158
                };
                img.Source    = picLocation;
                Image1.Source = picLocation;
                //Clone the stream and use this to run api call
                rasClone = ras.CloneStream();
            }
        }
Ejemplo n.º 6
0
        private async Task <Stream> WriteToStreamAsync(CapturedFrame frame)
        {
            using (var outputStream = new InMemoryRandomAccessStream())
            {
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, outputStream);

                encoder.IsThumbnailGenerated = false;
                encoder.SetSoftwareBitmap(frame.SoftwareBitmap);

                try
                {
                    await encoder.FlushAsync();
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                }

                await outputStream.FlushAsync();

                var ms = new MemoryStream();
                await outputStream.AsStream().CopyToAsync(ms);

                ms.Position = 0;

                return(ms);
            }
        }
Ejemplo n.º 7
0
        private async void SetImage(byte[] ImageData)
        {
            MedicalCanvas.Children.Clear();
            if (ImageData == null)
            {
                MedcialInkManager = new InkManager();
                return;
            }
            InkManager inkMgr = MedcialInkManager;

            renderer = new XamlInkRenderer(MedicalCanvas);

            using (var stream = new InMemoryRandomAccessStream())
            {
                await stream.WriteAsync(ImageData.AsBuffer());

                await stream.FlushAsync();

                stream.Seek(0);

                await inkMgr.LoadAsync(stream);

                var iskList  = inkMgr.GetStrokes();
                int iskCount = iskList.Count;
                renderer.Clear();
                renderer.AddInk(iskList);
            }
        }
Ejemplo n.º 8
0
        private async static void UriSourcePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Debug.WriteLine("我被触发了");
            StorageCachedImage image = d as StorageCachedImage;
            string             i     = e.NewValue as string;
            int    k         = i.IndexOf("image");
            string imagePath = i.Substring(k + 7);
            string uri       = App.Uri + "public/images/" + imagePath;

            Debug.WriteLine(uri);


            Uri imageUri = new Uri(uri);

            HttpClient client   = new HttpClient();
            var        response = await client.GetAsync(imageUri);

            var buffer = await response.Content.ReadAsBufferAsync();

            var memoryStream = new InMemoryRandomAccessStream();
            await memoryStream.WriteAsync(buffer);

            await memoryStream.FlushAsync();

            await image.SetSourceAsync(memoryStream);
        }
Ejemplo n.º 9
0
 protected override void setLightweightMode(bool l)
 {
     if (lightweightMode != l)
     {
         lightweightMode = l;
         SilverlightImplementation.dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
         {
             if (l)
             {
                 if (element is WebView && element.Visibility == Visibility.Visible && element.RenderSize.Width > 0 && element.RenderSize.Height > 0)
                 {
                     IRandomAccessStream stream = new InMemoryRandomAccessStream();
                     CanvasBitmap cb            = null;
                     await((WebView)element).CapturePreviewToStreamAsync(stream);
                     await stream.FlushAsync();
                     stream.Seek(0);
                     lastWebViewPeerImage = await CanvasBitmap.LoadAsync(SilverlightImplementation.screen, stream);
                 }
                 element.Visibility = Visibility.Collapsed;
             }
             else
             {
                 element.Visibility = Visibility.Visible;
             }
         }).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
         getComponentForm().repaint();
     }
 }
Ejemplo n.º 10
0
        private async Task makeJpegAsync(BitmapDecoder decoder, byte[] pixelBytes, pdfPage page, BitmapImage bitmapImage, int x, int y)
        {
            //double jpegImageQuality = Constants.ImageAttachStartingImageQuality;
            double jpegImageQuality = 0.9;
            ulong  jpegImageSize    = 0;

            var imageWriteableStream = new InMemoryRandomAccessStream();

            //MemoryStream memoryStream = new MemoryStream();
            //var imageWriteableStream = memoryStream.AsRandomAccessStream();

            using (imageWriteableStream)
            {
                var propertySet  = new BitmapPropertySet();
                var qualityValue = new BitmapTypedValue(jpegImageQuality, Windows.Foundation.PropertyType.Single);
                propertySet.Add("ImageQuality", qualityValue);

                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, imageWriteableStream, propertySet);

                //key thing here is to use decoder.OrientedPixelWidth and decoder.OrientedPixelHeight otherwise you will get garbled image on devices on some photos with orientation in metadata
                encoder.SetPixelData(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, decoder.OrientedPixelWidth, decoder.OrientedPixelHeight, decoder.DpiX, decoder.DpiY, pixelBytes);

                jpegImageSize = imageWriteableStream.Size;

                await encoder.FlushAsync();

                await imageWriteableStream.FlushAsync();

                var byteArray = new byte[imageWriteableStream.Size];
                await imageWriteableStream.ReadAsync(byteArray.AsBuffer(), (uint)imageWriteableStream.Size, InputStreamOptions.None);

                //page.addImage(bitmapImage, byteArray, x, y);
                page.addImage(imageWriteableStream);
            }
        }
Ejemplo n.º 11
0
        protected override ui.Image generatePeerImage()
        {
            if (element is MediaElement)
            {
                return(null);
            }

            int width  = getWidth();
            int height = getHeight();

            if (width <= 0 || height <= 0)
            {
                width  = getPreferredW();
                height = getPreferredH();
            }
            CodenameOneImage img = new CodenameOneImage();

            img.name = "PeerImage: " + element.ToString();
            IRandomAccessStream stream = new InMemoryRandomAccessStream();
            CanvasBitmap        cb     = null;

            SilverlightImplementation.dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                if (element is WebView)
                {
                    if (lastWebViewPeerImage != null)
                    {
                        cb = lastWebViewPeerImage;
                    }
                    else if (element.Visibility == Visibility.Visible && element.RenderSize.Width > 0 && element.RenderSize.Height > 0)
                    {
                        await((WebView)element).CapturePreviewToStreamAsync(stream);
                        await stream.FlushAsync();
                        stream.Seek(0);
                        cb = await CanvasBitmap.LoadAsync(SilverlightImplementation.screen, stream);
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
                    await renderTargetBitmap.RenderAsync(element);
                    byte[] buf = renderTargetBitmap.GetPixelsAsync().AsTask().ConfigureAwait(false).GetAwaiter().GetResult().ToArray();

                    cb = CanvasBitmap.CreateFromBytes(SilverlightImplementation.screen, buf, width, height,
                                                      SilverlightImplementation.pixelFormat, SilverlightImplementation.screen.Dpi);
                }
                img.image = new CanvasRenderTarget(SilverlightImplementation.screen, (int)cb.SizeInPixels.Width, (int)cb.SizeInPixels.Height, cb.Dpi);
                img.graphics.destination.drawImage(cb, 0, 0);
                img.graphics.destination.dispose();
            }).AsTask().GetAwaiter().GetResult();
            if (cb == null)
            {
                return(null);
            }
            return(ui.Image.createImage(img));
        }
Ejemplo n.º 12
0
        public async void WriteXml(XmlWriter writer)
        {
            writer.WriteElementString("Title", Title);
            writer.WriteElementString("Description", Description);
            writer.WriteElementString("Status", Status.ToString());
            writer.WriteStartElement("Stokes");
            if (Strokes != null && Strokes.Count > 0)
            {
                using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
                {
                    InkStrokeContainer inkCont = new InkStrokeContainer();

                    foreach (InkStroke stroke in Strokes)
                    {
                        inkCont.AddStroke(stroke.Clone());
                    }

                    await inkCont.SaveAsync(ms);

                    await ms.FlushAsync();

                    byte[] bytes = new byte[ms.Size];
                    //var dataWriter = new DataWriter(ms);
                    var reader = new DataReader(ms.GetInputStreamAt(0));
                    await reader.LoadAsync((uint)ms.Size);

                    reader.ReadBytes(bytes);

                    writer.WriteBinHex(bytes, 0, (int)ms.Size);
                }
            }
            writer.WriteEndElement();
        }
Ejemplo n.º 13
0
        /// <summary>
        /// 获取Jpg和Png图像
        /// </summary>
        /// <param name="randomAccessStream"></param>
        private async void JpegAndPng(InMemoryRandomAccessStream randomAccessStream)
        {
            var stop = this.Stop;

            this.Stop = true;
            bitFrame.Clear();
            await Task.Delay(TimeSpan.FromMilliseconds(15));

            randomAccessStream.Seek(0);
            await randomAccessStream.FlushAsync();

            this.imageGifGrid.Children.Clear();
            //优化
            this.imageList.Clear();
            this.bitmapImageList.Clear();

            Image       imageGif = new Image();
            BitmapImage bi       = new BitmapImage();

            imageGif.Source = null;
            await Task.Delay(TimeSpan.FromMilliseconds(15));

            //bi.SetSource(randomAccessStream);
            await bi.SetSourceAsync(randomAccessStream);

            imageGif.Stretch = this.Stretch;
            imageGif.Width   = this.width;
            imageGif.Height  = this.height;
            imageGif.Source  = bi;
            this.imageGifGrid.Children.Add(imageGif);
            this.Stop = stop;
        }
Ejemplo n.º 14
0
        private async Task BuildImageFrames()
        {
            while (isStreamingIn)
            {
                await Task.Delay(5);

                StreamedArraysQueue.TryDequeue(out byte[] buffer);

                if (!(buffer?.Any() ?? false))
                {
                    continue;
                }

                try
                {
                    var randomAccessStream = new InMemoryRandomAccessStream();
                    await randomAccessStream.WriteAsync(buffer.AsBuffer());

                    randomAccessStream.Seek(0);
                    await randomAccessStream.FlushAsync();

                    var decoder = await BitmapDecoder.CreateAsync(randomAccessStream);

                    var softwareBitmap = await decoder.GetSoftwareBitmapAsync();

                    var imageSource = await ConvertToSoftwareBitmapSource(softwareBitmap);

                    ImageVideo.Source = imageSource;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            }
        }
Ejemplo n.º 15
0
        public async void Stop()
        {
            await _mediaCapture.StopRecordAsync();

            await _memoryBuffer.FlushAsync();

            //sendAudioThread.Abort();
        }
Ejemplo n.º 16
0
        private async void LoadPdfFileAsync(StorageFile selectedFile)
        {
            // LogHelper.LogActivityDebug("EspaceTablette.Pages.PdfViewer.LoadPdfFileAsync | Entrée");

            _pdfDocument = await PdfDocument.LoadFromFileAsync(selectedFile);;

            ObservableCollection <SampleDataItem> l_items = new ObservableCollection <SampleDataItem>();

            this.DefaultViewModel["Items"] = l_items;

            if (_pdfDocument != null && _pdfDocument.PageCount > 0)
            {
                for (int l_pageIndex = 0; l_pageIndex < _pdfDocument.PageCount; l_pageIndex++)
                {
                    try
                    {
                        PdfPage l_pdfPage = _pdfDocument.GetPage((uint)l_pageIndex);
                        if (l_pdfPage != null)
                        {
                            BitmapImage l_imgSrc = new BitmapImage();

                            using (IRandomAccessStream l_randomStream = new InMemoryRandomAccessStream())
                            {
                                PdfPageRenderOptions l_pdfPageRenderOptions = new PdfPageRenderOptions();
                                l_pdfPageRenderOptions.DestinationWidth       = (uint)((Window.Current.Bounds.Width - 130) / ResolutionScale() * 100);
                                l_pdfPageRenderOptions.IsIgnoringHighContrast = true;

                                await l_pdfPage.RenderToStreamAsync(l_randomStream, l_pdfPageRenderOptions);

                                await l_randomStream.FlushAsync();

                                await l_imgSrc.SetSourceAsync(l_randomStream);
                            }
                            l_pdfPage.Dispose();

                            l_items.Add(new SampleDataItem(
                                            l_pageIndex.ToString(),
                                            l_pageIndex.ToString(),
                                            l_imgSrc));

                            Image l_printableImage = new Image();
                            l_printableImage.Stretch = Stretch.Uniform;
                            l_printableImage.Source  = l_imgSrc;

                            m_pages.Add(l_printableImage);
                            //inPage.CurrentPrintType = WebViewPage.PrintType.PdfDocument;
                        }
                    }
                    catch (Exception ex)
                    {
                        //if (App.Debug)
                        //{
                        //    LogHelper.LogActivityWithException(l_ex, "Exception");
                        //}
                    }
                }
            }
        }
Ejemplo n.º 17
0
        private async void TakePhoto_Click(object sender, RoutedEventArgs e)
        {
            if (!isCameraFound)
            {
                return;
            }

            try
            {
                using (var imageStream = new InMemoryRandomAccessStream())
                {
                    // capture photo and encode it
                    var encodingProperties = ImageEncodingProperties.CreateJpeg();
                    await this.mediaCapture.CapturePhotoToStreamAsync(encodingProperties, imageStream);

                    await imageStream.FlushAsync();

                    imageStream.Seek(0);

                    // display photo preview
                    var img = new BitmapImage();
                    img.SetSource(imageStream);
                    this.TakenPhoto.Source = img;

                    imageStream.Seek(0);

                    // call emotion API
                    var emotionServiceClient = new EmotionServiceClient(EmotionApiKey);
                    var emotionResult        = await emotionServiceClient.RecognizeAsync(imageStream.AsStreamForRead());

                    var emotionText = "Face [{0}]{1} Anger: {2:P2}{1} Contempt: {3:P2}{1} Disgust: {4:P2}{1} Fear: {5:P2}{1} Happiness: {6:P2}{1} Neutral: {7:P2}{1} Sadness: {8:P2}{1} Surprise: {9:P2}{1}";

                    // display emotion results
                    this.EmotionList.Items.Clear();
                    for (int i = 0; i < emotionResult.Length; i++)
                    {
                        var scores    = emotionResult[i].Scores;
                        var textBlock = new TextBlock()
                        {
                            TextWrapping = TextWrapping.WrapWholeWords
                        };
                        textBlock.Text = string.Format(emotionText, i, Environment.NewLine, scores.Anger, scores.Contempt, scores.Disgust, scores.Fear, scores.Happiness, scores.Neutral, scores.Sadness, scores.Surprise);
                        this.EmotionList.Items.Add(textBlock);
                    }
                }
            }
            catch (Exception ex)
            {
                var dialog = new Windows.UI.Popups.MessageDialog("Error while taking photo: " + ex.Message);
                await dialog.ShowAsync();

                GC.Collect();
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 异步从网络下载图片
        /// </summary>
        /// <param name="outfileName">下载保存到本地的图片文件名</param>
        /// <param name="downloadUriString">图片uri</param>
        /// <param name="scaleSize">图片尺寸</param>
        /// <returns></returns>
        public static async Task DownloadAndScale(string outfileName, string downloadUriString, Size scaleSize)
        {
            try
            {
                Uri        downLoadingUri = new Uri(downloadUriString); //创建uri对象
                HttpClient client         = new HttpClient();           //实例化httpclient对象
                using (var response = await client.GetAsync(downLoadingUri))
                {
                    var buffer = await response.Content.ReadAsBufferAsync();//从返回的数据中读取buffer

                    var memoryStream = new InMemoryRandomAccessStream();
                    await memoryStream.WriteAsync(buffer);                                                //将buffer写入memorystream

                    await memoryStream.FlushAsync();                                                      //刷新

                    var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(memoryStream); //解密文件流

                    //确定图片大小
                    var bt = new Windows.Graphics.Imaging.BitmapTransform();
                    bt.ScaledWidth  = (uint)scaleSize.Width;
                    bt.ScaledHeight = (uint)scaleSize.Height;
                    //得到像素数值
                    var pixelProvider = await decoder.GetPixelDataAsync(
                        decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, bt,
                        ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.ColorManageToSRgb);


                    //下面保存图片
                    // Now that we have the pixel data, get the destination file
                    var localFolder = ApplicationData.Current.LocalFolder;
                    //var resultsFolder = await localFolder.CreateFolderAsync("Results", CreationCollisionOption.OpenIfExists);
                    var scaledFile = await localFolder.CreateFileAsync(outfileName, CreationCollisionOption.ReplaceExisting);

                    using (var scaledFileStream = await scaledFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        var encoder = await BitmapEncoder.CreateAsync(
                            BitmapEncoder.JpegEncoderId, scaledFileStream);

                        var pixels = pixelProvider.DetachPixelData();
                        encoder.SetPixelData(
                            decoder.BitmapPixelFormat,
                            decoder.BitmapAlphaMode,
                            (uint)scaleSize.Width,
                            (uint)scaleSize.Height,
                            decoder.DpiX,
                            decoder.DpiY,
                            pixels
                            );
                        await encoder.FlushAsync();
                    }
                }
            }
            catch (Exception) { Debug.WriteLine("工具,图片异常"); }
        }
        private async Task LoadPendingTiles(TileSource tileSource, string sourceName)
        {
            PendingTile pendingTile;
            var         cache = Cache;

            if (cache == null || sourceName == null)
            {
                while (pendingTiles.TryDequeue(out pendingTile))
                {
                    await DownloadImage(pendingTile.Tile, pendingTile.Image, pendingTile.Uri, null);
                }
            }
            else
            {
                while (pendingTiles.TryDequeue(out pendingTile))
                {
                    var tile      = pendingTile.Tile;
                    var image     = pendingTile.Image;
                    var uri       = pendingTile.Uri;
                    var extension = Path.GetExtension(uri.LocalPath);

                    if (string.IsNullOrEmpty(extension) || extension == ".jpeg")
                    {
                        extension = ".jpg";
                    }

                    var cacheKey  = string.Format(@"{0}\{1}\{2}\{3}{4}", sourceName, tile.ZoomLevel, tile.XIndex, tile.Y, extension);
                    var cacheItem = await cache.GetAsync(cacheKey);

                    var loaded = false;

                    if (cacheItem == null || cacheItem.Expiration <= DateTime.UtcNow)
                    {
                        loaded = await DownloadImage(tile, image, uri, cacheKey);
                    }

                    if (!loaded && cacheItem != null && cacheItem.Buffer != null)
                    {
                        using (var stream = new InMemoryRandomAccessStream())
                        {
                            await stream.WriteAsync(cacheItem.Buffer);

                            await stream.FlushAsync();

                            stream.Seek(0);

                            await LoadImageFromStream(tile, image, stream);
                        }
                    }
                }
            }

            Interlocked.Decrement(ref taskCount);
        }
Ejemplo n.º 20
0
        private async void AnalyzeButton_Click(object sender, RoutedEventArgs e)
        {
            if (processingImage)
            {
                // Ignore button presses while processing the image
                return;
            }

            if (inCaptureState)
            {
                processingImage = true;
                inCaptureState  = false;

                // Make the 'Processing...' label visible
                canvasControl.Visibility = Visibility.Visible;
                AnalyzeButton.Content    = "...";

                canvasControl.Invalidate();

                var originalPhoto  = new InMemoryRandomAccessStream();
                var reencodedPhoto = new InMemoryRandomAccessStream();
                await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), originalPhoto);

                await originalPhoto.FlushAsync();

                originalPhoto.Seek(0);

                captureElement.Visibility = Visibility.Collapsed;

                // Store the captured photo as a Win2D type for later use
                photoCanvasBitmap = await CanvasBitmap.LoadAsync(canvasControl, originalPhoto);

                // Send the photo to Project Oxford to detect the faces
                lastCapturedFaces = await faceServiceClient.DetectAsync(originalPhoto.AsStreamForRead(), true, true, true, false);

                // Force the canvasControl to be redrawn now that the photo is available
                canvasControl.Invalidate();

                processingImage       = false;
                AnalyzeButton.Content = "Restart";
            }
            else
            {
                canvasControl.Visibility  = Visibility.Collapsed;
                captureElement.Visibility = Visibility.Visible;
                AnalyzeButton.Content     = "Capture Photo";

                photoCanvasBitmap = null;
                canvasControl.Invalidate();

                inCaptureState = true;
            }
        }
Ejemplo n.º 21
0
        //粤语发音
        private async void Voice_Click(object sender, RoutedEventArgs e)
        {
            TextToVoice temp  = new TextToVoice();
            Stream      voice = await temp.ReadText(Input.Text);

            InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
            await voice.CopyToAsync(ras.AsStreamForWrite());

            await ras.FlushAsync();

            ras.Seek(0);
            MyMediaPlayer.SetSource(ras, "");
        }
Ejemplo n.º 22
0
        ///
        ///  Name           ClearAudioFiles
        ///
        ///  <summary>     Clears the audio file after saving.
        ///  </summary>
        /// <returns></returns>
        public async void ClearAudioFiles()
        {
            try
            {
                await _buffer.FlushAsync();

                _buffer.Dispose();
            }
            catch (Exception ex)
            {
                LogTracking.LogTrace(ex.ToString());
            }
        }
        private async void Button_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            CanvasDevice       device       = CanvasDevice.GetSharedDevice();
            CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (int)inkDataCanvas.ActualWidth, (int)inkDataCanvas.ActualHeight, 96);

            using (var ds = renderTarget.CreateDrawingSession())
            {
                ds.Clear(Colors.Black);
                ds.DrawInk(inkDataCanvas.InkPresenter.StrokeContainer.GetStrokes());
            }

            using (var ms = new InMemoryRandomAccessStream())
            {
                await renderTarget.SaveAsync(ms, CanvasBitmapFileFormat.Jpeg, 1);

                await ms.FlushAsync();

                var decoder = await BitmapDecoder.CreateAsync(ms);

                var img = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore);

                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ms);

                encoder.BitmapTransform.ScaledHeight = 227;
                encoder.BitmapTransform.ScaledWidth  = 227;
                encoder.SetSoftwareBitmap(img);
                await encoder.FlushAsync();

                decoder = await BitmapDecoder.CreateAsync(ms);

                img = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore);

                img = SoftwareBitmap.Convert(img, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore);
                var model = await CustomGestureModel.CreateFromStreamAsync(await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///CustomGesture.onnx")));

                var output = await model.EvaluateAsync(new CustomGestureInput
                {
                    data = ImageFeatureValue.CreateFromVideoFrame(VideoFrame.CreateWithSoftwareBitmap(img))
                });

                if (output != null)
                {
                    var res   = output.classLabel.GetAsVectorView().ToList();
                    var label = res.FirstOrDefault();
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
                    {
                        await new MessageDialog(label).ShowAsync();
                    });
                }
            }
        }
Ejemplo n.º 24
0
        public static async Task <bool> SaveBytes(int id, String folderName, byte[] img, string extension, bool isTemp)
        {
            String fileName = String.Format("{0}.{1}", id, extension);

            try
            {
                using (var streamWeb = new InMemoryRandomAccessStream())
                {
                    using (var writer = new DataWriter(streamWeb.GetOutputStreamAt(0)))
                    {
                        writer.WriteBytes(img);
                        await writer.StoreAsync();

                        StorageFolder folder;
                        if (isTemp)
                        {
                            folder = ApplicationData.Current.TemporaryFolder;
                        }
                        else
                        {
                            folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists);
                        }

                        var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);

                        Debug.WriteLine("Writing file " + folderName + " " + id);
                        using (var raStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                        {
                            using (var thumbnailStream = streamWeb.GetInputStreamAt(0))
                            {
                                using (var stream = raStream.GetOutputStreamAt(0))
                                {
                                    await RandomAccessStream.CopyAsync(thumbnailStream, stream);

                                    await stream.FlushAsync();
                                }
                            }
                            await raStream.FlushAsync();
                        }
                        await writer.FlushAsync();
                    }
                    await streamWeb.FlushAsync();
                }
                return(true);
            }
            catch (Exception e)
            {
                Debug.WriteLine("Error saving bytes: " + e);
                return(false);
            }
        }
Ejemplo n.º 25
0
        public static async Task <BitmapImage> ConvertByteArrayToBitmapImage(byte[] byteValue)
        {
            var img = new BitmapImage();

            var ras = new InMemoryRandomAccessStream();
            await ras.WriteAsync(byteValue.AsBuffer());

            await ras.FlushAsync();

            ras.Seek(0);
            img.SetSource(ras);

            return(img);
        }
Ejemplo n.º 26
0
        private async Task <bool> LoadImageFromHttpResponse(HttpResponseMessage response, Tile tile, string cacheKey)
        {
            string tileInfo;

            if (response.Headers.TryGetValue("X-VE-Tile-Info", out tileInfo) && tileInfo == "no-tile") // set by Bing Maps
            {
                tile.SetImage(null);
                return(true);
            }

            using (var stream = new InMemoryRandomAccessStream())
            {
                using (var content = response.Content)
                {
                    await content.WriteToStreamAsync(stream);
                }

                await stream.FlushAsync();

                stream.Seek(0);

                var loaded = await LoadImageFromStream(tile, stream);

                if (loaded && cacheKey != null)
                {
                    var buffer = new Windows.Storage.Streams.Buffer((uint)stream.Size);

                    stream.Seek(0);
                    await stream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None);

                    var expiration = DefaultCacheExpiration;

                    if (response.Headers.CacheControl.MaxAge.HasValue)
                    {
                        expiration = response.Headers.CacheControl.MaxAge.Value;

                        if (expiration < MinimumCacheExpiration)
                        {
                            expiration = MinimumCacheExpiration;
                        }
                    }

                    await Cache.SetAsync(cacheKey, buffer, DateTime.UtcNow.Add(expiration));
                }

                return(loaded);
            }
        }
Ejemplo n.º 27
0
        public static async Task <IRandomAccessStream> UnprotectPDFStream(IRandomAccessStream source)
        {
            // Create a DataProtectionProvider object.
            DataProtectionProvider Provider = new DataProtectionProvider();

            InMemoryRandomAccessStream unprotectedData = new InMemoryRandomAccessStream();
            IOutputStream dest = unprotectedData.GetOutputStreamAt(0);

            await Provider.UnprotectStreamAsync(source.GetInputStreamAt(0), dest);

            await unprotectedData.FlushAsync();

            unprotectedData.Seek(0);

            return(unprotectedData);
        }
Ejemplo n.º 28
0
        public async void GetSharedData(DataTransferManager sender, DataRequestedEventArgs args)
        {
            try
            {
                var cam = _tomTomApi.TomTomViewModel.SelectedCamera;
                if ((cam != null) && (cam.TimeLapse.Count > 0))
                {
                    DataRequestDeferral deferral = args.Request.GetDeferral();

                    args.Request.Data.Properties.Title       = String.Format("TomTom Camera: {0}", cam.CameraId);
                    args.Request.Data.Properties.Description = cam.Name;

                    // share a file
                    var file = await StorageFile.CreateStreamedFileAsync(
                        String.Format("{0}_{1}.jpg", cam.CameraId, DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss")),
                        async stream =>
                    {
                        await stream.WriteAsync(cam.LastImageBytes.AsBuffer());
                        await stream.FlushAsync();
                        stream.Dispose();
                    },
                        null);

                    args.Request.Data.SetStorageItems(new List <IStorageItem> {
                        file
                    });

                    // share as bitmap
                    InMemoryRandomAccessStream raStream = new InMemoryRandomAccessStream();
                    await raStream.WriteAsync(cam.LastImageBytes.AsBuffer());

                    await raStream.FlushAsync();

                    args.Request.Data.SetBitmap(RandomAccessStreamReference.CreateFromStream(raStream));

                    deferral.Complete();
                }
                else
                {
                    args.Request.FailWithDisplayText("Select a camera to share its latest image.");
                }
            }
            catch (Exception ex)
            {
                args.Request.FailWithDisplayText(ex.Message);
            }
        }
Ejemplo n.º 29
0
        public async Task <byte[]> CapturePhoto()
        {
            using (var captureStream = new InMemoryRandomAccessStream())
            {
                await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);

                await captureStream.FlushAsync();

                captureStream.Seek(0);

                var readStream   = captureStream.AsStreamForRead();
                var imageInBytes = new byte[readStream.Length];
                await readStream.ReadAsync(imageInBytes, 0, imageInBytes.Length);

                return(imageInBytes);
            }
        }
        private async void InkPresenter_StrokesCollected(InkPresenter sender, InkStrokesCollectedEventArgs args)
        {
            CanvasDevice       device       = CanvasDevice.GetSharedDevice();
            CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (int)inkDataCanvas.ActualWidth, (int)inkDataCanvas.ActualHeight, 96);

            using (var ds = renderTarget.CreateDrawingSession())
            {
                ds.Clear(Colors.Black);
                ds.DrawInk(inkDataCanvas.InkPresenter.StrokeContainer.GetStrokes());
            }

            using (var ms = new InMemoryRandomAccessStream())
            {
                await renderTarget.SaveAsync(ms, CanvasBitmapFileFormat.Jpeg, 1);

                await ms.FlushAsync();

                var decoder = await BitmapDecoder.CreateAsync(ms);

                var img = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore);

                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ms);

                encoder.BitmapTransform.ScaledHeight = (uint)ViewModelLocator.Instance.Main.ImageSize;
                encoder.BitmapTransform.ScaledWidth  = (uint)ViewModelLocator.Instance.Main.ImageSize;
                encoder.SetSoftwareBitmap(img);
                await encoder.FlushAsync();

                decoder = await BitmapDecoder.CreateAsync(ms);

                img = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore);

                img = SoftwareBitmap.Convert(img, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore);

                var sbs = new SoftwareBitmapSource();
                await sbs.SetBitmapAsync(img);

                inkImage.Source = sbs;

                //var targetImage = new SoftwareBitmap(BitmapPixelFormat.Bgra8, img.PixelWidth, img.PixelHeight);
                // img.CopyTo(targetImage);
                ViewModelLocator.Instance.Main.CurrentInkImage = ms.CloneStream();
                ms.Dispose();
            }
        }