private async void button_Click(object sender, RoutedEventArgs e) { CameraCaptureUI captureUI = new CameraCaptureUI(); captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg; captureUI.PhotoSettings.CroppedSizeInPixels = new Size(200, 200); StorageFile photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo); if (photo == null) { // User cancelled photo capture return; } IRandomAccessStream stream = await photo.OpenAsync(FileAccessMode.Read); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync(); SoftwareBitmap softwareBitmapBGR8 = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); SoftwareBitmapSource bitmapSource = new SoftwareBitmapSource(); await bitmapSource.SetBitmapAsync(softwareBitmapBGR8); imageControl.Source = bitmapSource; }
public async Task<SoftwareBitmapSource> ConvertToSoftwareBitmapSource(SoftwareBitmap bitmap) { SoftwareBitmapSource bitmapSource = new SoftwareBitmapSource(); await bitmapSource.SetBitmapAsync(bitmap); return bitmapSource; }
private async void BrowsePhotoButton_Click(object sender, RoutedEventArgs 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) { photoStream = await camera.ConvertToStream(file); photoBitmap = await camera.ConvertToSoftwareBitmap(photoStream); photoBitmapSource = await camera.ConvertToSoftwareBitmapSource(photoBitmap); } }
/// <summary> /// Trigger file picker and image evaluation /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void ButtonRun_Click(object sender, RoutedEventArgs e) { ButtonRun.IsEnabled = false; UIPreviewImage.Source = null; StatusBlock.Text = "Loading image..."; try { // Trigger file picker to select an image file FileOpenPicker fileOpenPicker = new FileOpenPicker(); fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; fileOpenPicker.FileTypeFilter.Add(".jpg"); fileOpenPicker.FileTypeFilter.Add(".png"); fileOpenPicker.ViewMode = PickerViewMode.Thumbnail; StorageFile selectedStorageFile = await fileOpenPicker.PickSingleFileAsync(); SoftwareBitmap softwareBitmap; using (IRandomAccessStream stream = await selectedStorageFile.OpenAsync(FileAccessMode.Read)) { // Create the decoder from the stream BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); // Get the SoftwareBitmap representation of the file in BGRA8 format softwareBitmap = await decoder.GetSoftwareBitmapAsync(); softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); } // Display the image SoftwareBitmapSource imageSource = new SoftwareBitmapSource(); await imageSource.SetBitmapAsync(softwareBitmap); UIPreviewImage.Source = imageSource; // Encapsulate the image within a VideoFrame to be bound and evaluated VideoFrame inputImage = VideoFrame.CreateWithSoftwareBitmap(softwareBitmap); await EvaluateVideoFrameAsync(inputImage); } catch (Exception ex) { StatusBlock.Text = $"error: {ex.Message}"; ButtonRun.IsEnabled = true; } }
/// <summary> /// Configure an IFrameSource from a StorageFile or MediaCapture instance to produce optionally a specified format of frame /// </summary> /// <param name="source"></param> /// <param name="inputImageDescriptor"></param> /// <returns></returns> private async Task ConfigureFrameSourceAsync(object source, ISkillFeatureImageDescriptor inputImageDescriptor = null) { await m_lock.WaitAsync(); { // Reset bitmap rendering component UIProcessedPreview.Source = null; m_renderTargetFrame = null; m_processedBitmapSource = new SoftwareBitmapSource(); UIProcessedPreview.Source = m_processedBitmapSource; // Clean up previous frame source if (m_frameSource != null) { m_frameSource.FrameArrived -= FrameSource_FrameAvailable; var disposableFrameSource = m_frameSource as IDisposable; if (disposableFrameSource != null) { // Lock disposal based on frame source consumers disposableFrameSource.Dispose(); } } // Create new frame source and register a callback if the source fails along the way m_frameSource = await FrameSourceFactory.CreateFrameSourceAsync( source, (sender, message) => { NotifyUser(message); }, inputImageDescriptor); // TODO: Workaround for a bug in ObjectDetectorBinding when binding consecutively VideoFrames with Direct3DSurface and SoftwareBitmap m_binding = await m_skill.CreateSkillBindingAsync() as ObjectDetectorBinding; } m_lock.Release(); // If we obtained a valid frame source, start it if (m_frameSource != null) { m_frameSource.FrameArrived += FrameSource_FrameAvailable; await m_frameSource.StartAsync(); } }
private async void SoftwareBitmapToWriteableBitmap(SoftwareBitmap softwareBitmap) { softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight); // CHANGE THIS SNIPPET NAME - LEAVING NOW TO AVOID RISK OF BUILD BREAK // <SnippetSoftwareBitmapToWriteableBitmap> if (softwareBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 || softwareBitmap.BitmapAlphaMode == BitmapAlphaMode.Straight) { softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); } var source = new SoftwareBitmapSource(); await source.SetBitmapAsync(softwareBitmap); // Set the source of the Image control imageControl.Source = source; // </SnippetSoftwareBitmapToWriteableBitmap> }
private async Task <bool> Classify(Image image) { var bitmapSource = new SoftwareBitmapSource(); editPreview.Source = bitmapSource; var histogram = await ComputeHistogramWithDisplay(image, bitmapSource, TimeSpan.FromMilliseconds(500)); var emptyOutputs = new List <double>() { 0, 0, 0, 0, 0, 0 }; _classifier.ChangeData(histogram, emptyOutputs); var classification = _classifier.GetClassification(); ClassTextBlock.Text = Folders.PlantNames[classification.Item1] + " Class"; ConfidenceTextBlock.Text = classification.Item2 + "% Confidence"; return(true); }
private async void ScaleRainbowButton_Click(object sender, RoutedEventArgs e) { SoftwareBitmap tempSB; double scale = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel; int renderTB_Width = 200; int renderTB_Height = 100; int newWidth = g704_softwareBitmap.PixelWidth; int newHeight = g704_softwareBitmap.PixelHeight; // Step 1 : // Create RenderTargetBitmap by ColorRectangle. // Don't worry about both width and height of ColorRectangle. RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(); ColorRectangle.Fill = MyColorHelper.GetRainbowBrush(); await renderTargetBitmap.RenderAsync(ColorRectangle, renderTB_Width, renderTB_Height); // Step 2 : // Get IBuffer from RenderTargetBitmap, IBuffer ib = await renderTargetBitmap.GetPixelsAsync(); // Step 3 : // Create a temporary SoftwareBitmap which is based on current scale tempSB = SoftwareBitmap.CreateCopyFromBuffer(ib, BitmapPixelFormat.Bgra8, (int)(renderTB_Width * scale), (int)(renderTB_Height * scale)); tempSB = SoftwareBitmap.Convert(tempSB, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); // Step 4 : // Adjust to the same size as g704 image tempSB = Resize(tempSB, newWidth, newHeight); // Step 5 : // Assign this temp image pixels to g704 image g704_softwareBitmap = SoftwareBitmap.Convert(g704_softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight); AssignPixelValues(g704_softwareBitmap, tempSB); g704_softwareBitmap = SoftwareBitmap.Convert(g704_softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); var source = new SoftwareBitmapSource(); await source.SetBitmapAsync(g704_softwareBitmap); G704.Source = source; }
/// <summary> /// Trigger take photo and recognize the emotion present in the image /// </summary> private async void ButtonRun_Click(object sender, RoutedEventArgs e) { try { // Prepare and capture photo var lowLagCapture = await mediaCapture.PrepareLowLagPhotoCaptureAsync(ImageEncodingProperties.CreateUncompressed(MediaPixelFormat.Bgra8)); var capturedPhoto = await lowLagCapture.CaptureAsync(); var softwareBitmap = capturedPhoto.Frame.SoftwareBitmap; await lowLagCapture.FinishAsync(); // Display the captured image var imageSource = new SoftwareBitmapSource(); var displayableImage = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); await imageSource.SetBitmapAsync(displayableImage); PreviewImage.Source = imageSource; // Crop, Resize and Convert to gray scale the image (FERPlus model expects a grayscale image of 64x64 pixels) var rgbaImage = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied); var mindim = Math.Min(rgbaImage.PixelWidth, rgbaImage.PixelHeight); var croppedBitmap = CropSoftwareBitmap(rgbaImage, rgbaImage.PixelWidth / 2 - mindim / 2, rgbaImage.PixelHeight / 2 - mindim / 2, mindim, mindim); var scaledBitmap = ResizeSoftwareBitmap(croppedBitmap, 64, 64); var grayscaleBitmap = SoftwareBitmap.Convert(scaledBitmap, BitmapPixelFormat.Gray8, BitmapAlphaMode.Ignore); // Finally, Predict the dominat emotion present in the image (assuming that the image predominatly shows a face) VideoFrame inputImage = VideoFrame.CreateWithSoftwareBitmap(grayscaleBitmap); await Task.Run(async() => { // Evaluate the image await EvaluateVideoFrameAsync(inputImage); }); } catch (Exception ex) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => StatusBlock.Text = $"error: {ex.Message}"); } }
private async Task CapturePhotoAsync() { var lowlagCapture = await _mediaCapture.PrepareLowLagPhotoCaptureAsync(ImageEncodingProperties.CreateUncompressed(MediaPixelFormat.Bgra8)); var capturedPhoto = await lowlagCapture.CaptureAsync(); var softwareBitmap = capturedPhoto.Frame.SoftwareBitmap; var softwareBitmapSource = new SoftwareBitmapSource(); await softwareBitmapSource.SetBitmapAsync(SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied)); await lowlagCapture.FinishAsync(); _isPreviewing = false; /*var filename = "pb" + DateTime.Now.ToString("ssmmHHddMMyy") + ".bmp"; * var file = await savePicturesFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); * await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), file); * * IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read); * BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); * SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync(); * SoftwareBitmapSource softwareBitmapSource = new SoftwareBitmapSource(); * await softwareBitmapSource.SetBitmapAsync(SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied));*/ activepicture.Source = softwareBitmapSource; images.Add(softwareBitmap); await CleanupCameraAsync(); if (picstaken < totpics) { picstaken++; activepicture = (Image)this.FindName("image" + picstaken.ToString()); await StartPreviewAsync(); } else { complete = true; StartButton.Visibility = Visibility.Visible; dispatchTimer.Stop(); mergePhotos(); } }
public static void BindSoftwareBitmapToImageControl(Microsoft.UI.Xaml.Controls.Image imageControl, SoftwareBitmap softwareBitmap) { SoftwareBitmap displayBitmap = softwareBitmap; //Image control only accepts BGRA8 encoding and Premultiplied/no alpha channel. This checks and converts //the SoftwareBitmap we want to bind. if (displayBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 || displayBitmap.BitmapAlphaMode != BitmapAlphaMode.Premultiplied) { displayBitmap = SoftwareBitmap.Convert(displayBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); } // get software bitmap souce var source = new SoftwareBitmapSource(); source.SetBitmapAsync(displayBitmap).GetAwaiter(); // draw the input image imageControl.Source = source; }
protected override async void OnNavigatedTo(NavigationEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = rootFrame.CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed; base.OnNavigatedTo(e); var softwareBitmap = SoftwareBitmap.Convert((SoftwareBitmap)e.Parameter, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); bitmap = softwareBitmap; alteredImage = bitmap; var source = new SoftwareBitmapSource(); await source.SetBitmapAsync(softwareBitmap); imageControl.Source = source; }
private async void file2SoftwareBitmapSource(StorageFile file, int index = 0, bool isAddImage = false) { if (!isAddImage) { IStorageFolder applicationFolder = ApplicationData.Current.TemporaryFolder; await file.CopyAndReplaceAsync(await applicationFolder.CreateFileAsync(file.Name, CreationCollisionOption.ReplaceExisting)); } SoftwareBitmapSource source = new SoftwareBitmapSource(); SoftwareBitmap sb = null; using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read)) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); sb = softwareBitmap; } await source.SetBitmapAsync(sb); imageList.Insert(index, new CommunityImageList { imgUri = source, imgName = file.Name, imgPath = file.Path, imgAppPath = "ms-appdata:///Temp/" + file.Name }); }
private async void mostrarFoto(StorageFile file) { IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync(); SoftwareBitmap softwareBitmapBGR8 = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); SoftwareBitmapSource bitmapSource = new SoftwareBitmapSource(); await bitmapSource.SetBitmapAsync(softwareBitmapBGR8); Image ima = new Image(); ima.Source = bitmapSource; editImage.Source = bitmapSource; }
private void RenderImageInMainPanel(SoftwareBitmap softwareBitmap) { SoftwareBitmap displayBitmap = softwareBitmap; //Image control only accepts BGRA8 encoding and Premultiplied/no alpha channel. This checks and converts //the SoftwareBitmap we want to bind. if (displayBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 || displayBitmap.BitmapAlphaMode != BitmapAlphaMode.Premultiplied) { displayBitmap = SoftwareBitmap.Convert(displayBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); } // get software bitmap souce var source = new SoftwareBitmapSource(); source.SetBitmapAsync(displayBitmap).GetAwaiter(); // draw the input image InputImage.Source = source; }
public static async Task <SoftwareBitmapSource> LoadReceiptBitmapSource(StorageFile mFile) { if (mFile != null) { using (var stream = await mFile.OpenAsync(FileAccessMode.Read)) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); SoftwareBitmap sBitmap = await decoder.GetSoftwareBitmapAsync(); SoftwareBitmap softwareBitmapBGR8 = SoftwareBitmap.Convert(sBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); SoftwareBitmapSource bitmapSource = new SoftwareBitmapSource(); await bitmapSource.SetBitmapAsync(softwareBitmapBGR8); return(bitmapSource); } } return(null); }
private async void TakeSnapshot(object sender, RoutedEventArgs e) { var bitmap = FixBitmapForBGRA8(SnapshotVidoEffect.GetSnapShot()); var source = new SoftwareBitmapSource(); await source.SetBitmapAsync(bitmap); var newSnapshot = new ViewImageEditorMetadata(); newSnapshot.Bitmap = bitmap; newSnapshot.Source = source; newSnapshot.Number = snapshots.Count + 1; var pos = mePlayer.Position; newSnapshot.Position = new TimeSpan(pos.Days, pos.Hours, pos.Minutes, pos.Seconds);; snapshots.Add(newSnapshot); SendSystemNotification("Snapshot taken!"); }
private async Task <Comment> parseSingleComment(HtmlNode node) { HtmlNode commentSection = node.SelectSingleNode(".//section"); Comment resultComment = new Comment(); if (!isAttributeValueContains(commentSection.Attributes, "class", "comment-bad")) { SoftwareBitmapSource source = new SoftwareBitmapSource(); await source.SetBitmapAsync( await webManager.getCachedImageAsync(normalizeImageUriDebug( commentSection.SelectSingleNode(".//ul[@class='comment-info']") .SelectSingleNode(".//img[@class='comment-avatar']") .Attributes["src"].Value))); resultComment.id = int.Parse(commentSection.Attributes["data-id"].Value); if (isAttributeValueContains(commentSection.Attributes, "class", "comment-new")) { resultComment.isRead = false; } resultComment.text = await htmlParser.convertNodeToParagraph(commentSection.SelectSingleNode(".//div[@class='text']")); resultComment.author = commentSection.SelectSingleNode(".//ul[@class='comment-info']") .SelectSingleNode("./li") .InnerText .Trim(); resultComment.author_image = source; resultComment.datetime = commentSection.SelectSingleNode(".//time").InnerText.Replace("\n", String.Empty).Trim(); resultComment.rating = int.Parse(commentSection.SelectSingleNode(".//span[@class='vote-count']").InnerText); } else { resultComment.id = int.Parse(commentSection.Attributes["data-id"].Value); resultComment.text = await htmlParser.convertNodeToParagraph(commentSection.SelectSingleNode(".//div[@class='text']")); } return(resultComment); }
/// <summary> /// Configure an IFrameSource from a StorageFile or MediaCapture instance to produce optionally a specified format of frame /// </summary> /// <param name="source"></param> /// <returns></returns> private async Task ConfigureFrameSourceAsync(object source, ISkillFeatureImageDescriptor inputImageDescriptor = null) { await m_lock.WaitAsync(); { // Reset bitmap rendering component UIImageViewer.Source = null; m_renderTargetFrame = null; m_processedBitmapSource = new SoftwareBitmapSource(); UIImageViewer.Source = m_processedBitmapSource; m_bodyRenderer.IsVisible = false; // Clean up previous frame source if (m_frameSource != null) { m_frameSource.FrameArrived -= FrameSource_FrameAvailable; var disposableFrameSource = m_frameSource as IDisposable; if (disposableFrameSource != null) { // Lock disposal based on frame source consumers disposableFrameSource.Dispose(); } } // Create new frame source and register a callback if the source fails along the way m_frameSource = await FrameSourceFactory.CreateFrameSourceAsync( source, (sender, message) => { NotifyUser(message); }, inputImageDescriptor); } m_lock.Release(); // If we obtained a valid frame source, start it if (m_frameSource != null) { m_frameSource.FrameArrived += FrameSource_FrameAvailable; await m_frameSource.StartAsync(); } }
private async Task ExecuteBrowsePictureCommandAsync() { try { FileOpenPicker fileOpenPicker = new FileOpenPicker() { SuggestedStartLocation = PickerLocationId.PicturesLibrary, ViewMode = PickerViewMode.Thumbnail }; fileOpenPicker.FileTypeFilter.Add(".jpg"); fileOpenPicker.FileTypeFilter.Add(".jpeg"); fileOpenPicker.FileTypeFilter.Add(".png"); fileOpenPicker.FileTypeFilter.Add(".bmp"); IReadOnlyList <StorageFile> selectedFiles = await fileOpenPicker.PickMultipleFilesAsync(); if (selectedFiles != null) { foreach (var item in selectedFiles) { SoftwareBitmap softwareBitmap; using (IRandomAccessStream stream = await item.OpenAsync(FileAccessMode.Read)) { // Create the decoder from the stream BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); // Get the SoftwareBitmap representation of the file softwareBitmap = await decoder.GetSoftwareBitmapAsync(); softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); var softwareBitmapSource = new SoftwareBitmapSource(); await softwareBitmapSource.SetBitmapAsync(softwareBitmap); Pictures.Add(new BitmapWrapper(softwareBitmap, softwareBitmapSource)); } } } } catch (Exception ex) { await new MessageDialog(ex.Message).ShowAsync(); } }
private async void UpdatePhotoElements() { BtnPhoto.Content = "Replace Photo"; BtnDeletePhoto.Visibility = Visibility.Visible; RowPhoto.Height = new GridLength(1, GridUnitType.Star); ProgRing.IsActive = true; SoftwareBitmapSource mSource = await PhotoFunctions.LoadReceiptBitmapSource(capturedPhoto); if (mSource != null) { ImgReceipt.Source = mSource; } else { RowPhoto.Height = new GridLength(0); } ProgRing.IsActive = false; }
private async Task SetCurrentFile(string file) { loadingBorder.Visibility = Visibility.Visible; var streamTask = provider.OpenEntryAsRandomAccessStreamAsync(file); var stream = await streamTask; SoftwareBitmap bitmap = await CreateResizedBitmap(stream, (uint)canvas.RenderSize.Width, (uint)canvas.RenderSize.Height); var source = new SoftwareBitmapSource(); var setSourceTask = source.SetBitmapAsync(bitmap); image.Source = source; imageControl.Filename = ExtractFilename(file); await setSourceTask; loadingBorder.Visibility = Visibility.Collapsed; imageBorder.Visibility = Visibility.Visible; }
/// <summary> /// Evalutaes the builder. /// If invalid, lissts the problems. /// If valid, builds a landscape and generates the output (if the layer is present) /// </summary> public async Task Run() { const string nln = "\n"; LandscapeBuilder landscapeBuilder = BuildLandscapeBuilder(); await Output.SetAsync(string.Join(nln, landscapeBuilder.GetFullReport())); if (landscapeBuilder.IsValid()) { await Output.SetAsync(Output.Value + nln + "=== VALID ==="); Landscape landscape = landscapeBuilder.Build(); try { HeightMapImageOutputter outputter = (HeightMapImageOutputter)landscape.GetOutputter <byte[]>("img"); await Output.SetAsync(Output.Value + nln + "Generating the landscape."); byte[] bytes = outputter.GetObject(new Coordinate()); await Output.SetAsync(Output.Value + nln + "Generating the image."); await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() => { LatestBitmap = outputter.BytesToBitmap(bytes); if (LatestBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 || LatestBitmap.BitmapAlphaMode == BitmapAlphaMode.Straight) { LatestBitmap = SoftwareBitmap.Convert(LatestBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); } SoftwareBitmapSource source = new SoftwareBitmapSource(); await source.SetBitmapAsync(LatestBitmap); SoftwareBitmapSource.SetFromUIThread(source); }).AsTask(); await Output.SetAsync(Output.Value + nln + "Preview is ready,"); } catch (Exception err) { await Output.SetAsync(Output.Value + nln + "Failed to retrieve the Bitmap Outputter." + nln + "To enable the preview add a HeightMapImageOutputterBuilder with id of \"img\"" + nln + err.Message); } } else { await Output.SetAsync(Output.Value + nln + "=== INVALID ==="); } }
public async Task <ImageSource> GetImageSourceAsync() { if (_decoder != null) { switch (_decoder.BitmapPixelFormat) { case BitmapPixelFormat.Unknown: break; case BitmapPixelFormat.Rgba16: break; case BitmapPixelFormat.Rgba8: break; case BitmapPixelFormat.Gray16: break; case BitmapPixelFormat.Gray8: break; case BitmapPixelFormat.Bgra8: break; case BitmapPixelFormat.Nv12: break; case BitmapPixelFormat.Yuy2: break; default: break; } var bitmap = await _decoder.GetSoftwareBitmapAsync(); var source = new SoftwareBitmapSource(); await source.SetBitmapAsync(bitmap); } return(default(ImageSource)); }
private async void Button_Click(object sender, RoutedEventArgs e) { UIPreviewImage.Source = null; ResultText.Visibility = Visibility.Collapsed; try { // Get image using FileOpenPicker var fileOpenPicker = new FileOpenPicker(); fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; fileOpenPicker.FileTypeFilter.Add(".jpg"); fileOpenPicker.FileTypeFilter.Add(".jpeg"); fileOpenPicker.FileTypeFilter.Add(".png"); fileOpenPicker.ViewMode = PickerViewMode.Thumbnail; var selectedStorageFile = await fileOpenPicker.PickSingleFileAsync(); // Change image to SoftwareBitmap to show in AppPage SoftwareBitmap softwareBitmap; using (var stream = await selectedStorageFile.OpenAsync(FileAccessMode.Read)) { var decoder = await BitmapDecoder.CreateAsync(stream); softwareBitmap = await decoder.GetSoftwareBitmapAsync(); softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); } // Show image on AppPage var imageSource = new SoftwareBitmapSource(); await imageSource.SetBitmapAsync(softwareBitmap); UIPreviewImage.Source = imageSource; // Change image from SoftwareBitmap to VideoFrame var inputImage = VideoFrame.CreateWithSoftwareBitmap(softwareBitmap); await EvaluateVideoFrameAsync(inputImage); } catch (Exception ex) { } }
private async void DisplayImage(byte[] img) { /* * var jpgImage = new Byte[img.Count * PACKET_SIZE]; * for (int i = 0; i < img.Count; ++i) * { * for (int j = 0; j < img[i].Length; ++j) * { * jpgImage[(i * PACKET_SIZE) + j] = img[i][j]; * } * } */ try { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(ConvertTo(img)); SoftwareBitmap sftwareBmp = await decoder.GetSoftwareBitmapAsync(); SoftwareBitmap displayableImage = SoftwareBitmap.Convert(sftwareBmp, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); // var data = await decoder.GetPixelDataAsync(); // var bytes = data.DetachPixelData(); await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { var source = new SoftwareBitmapSource(); await source.SetBitmapAsync(displayableImage); testImg.Source = source; } ); Debug.WriteLine("Displayed!"); } catch (Exception ex) { Debug.WriteLine(ex.Message); } serverDatagramSocket.MessageReceived += ServerDatagramSocket_MessageReceived; }
protected async override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); photo = (StorageFile)e.Parameter; Frame rootFrame = Window.Current.Content as Frame; MyProgressRing.IsActive = true; MyProgressRing.Visibility = Visibility.Visible; PageContent.Visibility = Visibility.Collapsed; IRandomAccessStream accessStream = await photo.OpenAsync(FileAccessMode.Read); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(accessStream); SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync(); SoftwareBitmap softwareBitmapBGR8 = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); SoftwareBitmapSource bitmapSource = new SoftwareBitmapSource(); await bitmapSource.SetBitmapAsync(softwareBitmapBGR8); Picture.Source = bitmapSource; var stream = await photo.OpenStreamForReadAsync(); var result = await AnalyzeImage(stream); this.DataContext = (result.Any()) ? result.First().Scores : null; if (DataContext == null) { await new Windows.UI.Popups.MessageDialog("No pude detectar ninguna cara :(").ShowAsync(); rootFrame.GoBack(); } MyProgressRing.IsActive = false; MyProgressRing.Visibility = Visibility.Collapsed; PageContent.Visibility = Visibility.Visible; }
/// <summary> /// Gets the current preview frame as a SoftwareBitmap, displays its properties in a TextBlock, and can optionally display the image /// in the UI and/or save it to disk as a jpg /// </summary> /// <returns></returns> private async Task GetPreviewFrameAsSoftwareBitmapAsync() { // Get information about the preview var previewProperties = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties; // Create the video frame to request a SoftwareBitmap preview frame var videoFrame = new VideoFrame(BitmapPixelFormat.Bgra8, (int)previewProperties.Width, (int)previewProperties.Height); // Capture the preview frame using (var currentFrame = await _mediaCapture.GetPreviewFrameAsync(videoFrame)) { // Collect the resulting frame SoftwareBitmap previewFrame = currentFrame.SoftwareBitmap; // Show the frame information FrameInfoTextBlock.Text = String.Format("{0}x{1} {2}", previewFrame.PixelWidth, previewFrame.PixelHeight, previewFrame.BitmapPixelFormat); // Add a simple green filter effect to the SoftwareBitmap if (GreenEffectCheckBox.IsChecked == true) { ApplyGreenFilter(previewFrame); } // Show the frame (as is, no rotation is being applied) if (ShowFrameCheckBox.IsChecked == true) { // Create a SoftwareBitmapSource to display the SoftwareBitmap to the user var sbSource = new SoftwareBitmapSource(); await sbSource.SetBitmapAsync(previewFrame); // Display it in the Image control PreviewFrameImage.Source = sbSource; } // Save the frame (as is, no rotation is being applied) if (SaveFrameCheckBox.IsChecked == true) { await SaveSoftwareBitmapAsync(previewFrame); } } }
private async void addImageToGrid() { _images.getImages().ForEach(async image => { var backupImage = image; if (backupImage.BitmapPixelFormat != BitmapPixelFormat.Bgra8 || backupImage.BitmapAlphaMode == BitmapAlphaMode.Straight) { backupImage = SoftwareBitmap.Convert(backupImage, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); } Image imageChild = new Image(); var sbs = new SoftwareBitmapSource(); await sbs.SetBitmapAsync(backupImage); imageChild.Source = sbs; imageChild.Margin = new Thickness(20); imageChild.MaxWidth = 300; ImageGrid.Children.Add(imageChild); }); }
public NewItemPreview(StorageFile file, bool isVideo = false) { InitializeComponent(); var tmpFile = file; Task.Factory.StartNew(async() => { if (!isVideo) { using (IRandomAccessStream stream = await tmpFile.OpenAsync(FileAccessMode.Read)) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync(); SoftwareBitmap softwareBitmapBGR8 = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); SoftwareBitmapSource bitmapSource = new SoftwareBitmapSource(); await bitmapSource.SetBitmapAsync(softwareBitmapBGR8); ImagePreview.Source = bitmapSource; } } }, CancellationToken.None, TaskCreationOptions.None, DiskService.Client.Sync); }
private async void ImageLoaded(object sender, RoutedEventArgs r) { using (var stream = await item.path.OpenAsync(FileAccessMode.Read)) { var bitmapDecoder = await BitmapDecoder.CreateAsync(stream); var pixelProvider = await bitmapDecoder.GetPixelDataAsync(); bits = pixelProvider.DetachPixelData(); var softwareBitmap = new SoftwareBitmap( BitmapPixelFormat.Bgra8, (int)bitmapDecoder.PixelWidth, (int)bitmapDecoder.PixelHeight, BitmapAlphaMode.Premultiplied); softwareBitmap.CopyFromBuffer(bits.AsBuffer()); var softwareBitmapSource = new SoftwareBitmapSource(); await softwareBitmapSource.SetBitmapAsync(softwareBitmap); img.Source = softwareBitmapSource; } }
// </SnippetRegisterMetadataHandlerForImageSubtitles> // <SnippetImageSubtitleCueEntered> private async void metadata_ImageSubtitleCueEntered(TimedMetadataTrack timedMetadataTrack, MediaCueEventArgs args) { // Check in case there are different tracks and the handler was used for more tracks if (timedMetadataTrack.TimedMetadataKind == TimedMetadataKind.ImageSubtitle) { var cue = args.Cue as ImageCue; if (cue != null) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() => { var source = new SoftwareBitmapSource(); await source.SetBitmapAsync(cue.SoftwareBitmap); SubtitleImage.Source = source; SubtitleImage.Width = cue.Extent.Width; SubtitleImage.Height = cue.Extent.Height; SubtitleImage.SetValue(Canvas.LeftProperty, cue.Position.X); SubtitleImage.SetValue(Canvas.TopProperty, cue.Position.Y); }); } } }
private static async Task<ImageModel> Capture() { var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); // Get the desired camera by panel DeviceInformation desiredDevice = allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back); if (desiredDevice == null) { Debug.Write("no Camrea"); return null; } CameraCaptureUI cameraUI = new CameraCaptureUI(); cameraUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg; cameraUI.PhotoSettings.AllowCropping = false; //cameraUI.PhotoSettings.CroppedSizeInPixels = new Size(1280,720); StorageFile photo = await cameraUI.CaptureFileAsync(CameraCaptureUIMode.Photo); if (photo == null) return null; IRandomAccessStream stream = await photo.OpenAsync(FileAccessMode.Read); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); decoder = await BitmapDecoder.CreateAsync( await decoder.GetThumbnailAsync()); SoftwareBitmap bitmapBgr8 = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); SoftwareBitmapSource imgsource = new SoftwareBitmapSource(); await imgsource.SetBitmapAsync(bitmapBgr8); ImageModel imgModel = new ImageModel() { ImgFile = photo, ThumbnailImage = imgsource }; return imgModel; }
private async Task<SoftwareBitmapSource> PreparePhoto(StorageFile photo) { IRandomAccessStream stream = await photo.OpenAsync(FileAccessMode.Read); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync(); SoftwareBitmap softwareBitmapBGR8 = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); SoftwareBitmapSource bitmapSource = new SoftwareBitmapSource(); await bitmapSource.SetBitmapAsync(softwareBitmapBGR8); return bitmapSource; }
//callback funkcija kad se uslika public void SlikanjeGotovo(SoftwareBitmapSource slikica) { Slika = slikica; }
private async void CameraButton_Click(object sender, RoutedEventArgs e) { photoStream = await camera.TakePhoto(CameraCaptureUIPhotoFormat.Jpeg); photoBitmap = await camera.ConvertToSoftwareBitmap(photoStream); photoBitmapSource = await camera.ConvertToSoftwareBitmapSource(photoBitmap); }
async Task InitSize() { try { // this._file = await StorageHelper.TryGetFileFromPathAsync(path); if (this._file == null) return; var appView = ApplicationView.GetForCurrentView(); //this.gifViewer.Visibility = Visibility.Collapsed; this.Img.Visibility = Visibility.Visible; IInputStream inputStream = await this._file.OpenReadAsync(); IRandomAccessStream memStream = new InMemoryRandomAccessStream(); await RandomAccessStream.CopyAsync(inputStream, memStream); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(memStream); SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); if (softwareBitmap == null) return; SoftwareBitmapSource source = new SoftwareBitmapSource(); await source.SetBitmapAsync(softwareBitmap); if (softwareBitmap.PixelHeight > appView.VisibleBounds.Height || softwareBitmap.PixelWidth > appView.VisibleBounds.Width) { double ratio1, ratio2; ratio1 = (double)softwareBitmap.PixelWidth / (double)appView.VisibleBounds.Width; ratio2 = (double)softwareBitmap.PixelHeight / (double)appView.VisibleBounds.Height; if (ratio1 > ratio2) { this.Img.Width = appView.VisibleBounds.Width; this.Img.Height = softwareBitmap.PixelHeight / ratio1; if (ratio1 > 1.0) this.sv.MaxZoomFactor *= (float)ratio1; } else { this.Img.Width = softwareBitmap.PixelWidth / ratio2; this.Img.Height = appView.VisibleBounds.Height; if (ratio2 > 1.0) this.sv.MaxZoomFactor *= (float)ratio2; } } else { this.Img.Width = softwareBitmap.PixelWidth; this.Img.Height = softwareBitmap.PixelHeight; } this.sv.Width = appView.VisibleBounds.Width; this.sv.Height = appView.VisibleBounds.Height; } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } }
private void LoadIDButton_Click(object sender, RoutedEventArgs e) { idStream = photoStream; idBitmap = photoBitmap; idBitmapSource = photoBitmapSource; IDPhoto.Source = idBitmapSource; }
private static async Task<SoftwareBitmapSource> CropPhoto(StorageFile photo, FaceRectangle rectangle) { using (var imageStream = await photo.OpenReadAsync()) { var decoder = await BitmapDecoder.CreateAsync(imageStream); if (decoder.PixelWidth >= rectangle.Left + rectangle.Width || decoder.PixelHeight >= rectangle.Top + rectangle.Height) { var transform = new BitmapTransform { Bounds = new BitmapBounds { X = (uint)rectangle.Left, Y = (uint)rectangle.Top, Height = (uint)rectangle.Height, Width = (uint)rectangle.Width } }; var softwareBitmapBGR8 = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage); SoftwareBitmapSource bitmapSource = new SoftwareBitmapSource(); await bitmapSource.SetBitmapAsync(softwareBitmapBGR8); return bitmapSource; } return null; } }
//TODO:未登录时不能选择上传头像 private async void headimgRectangle_Tapped(object sender, TappedRoutedEventArgs e) { //if (appSetting.Values.ContainsKey("idNum")) try { var vault = new Windows.Security.Credentials.PasswordVault(); var credentialList = vault.FindAllByResource(resourceName); credentialList[0].RetrievePassword(); if (credentialList.Count > 0) { FileOpenPicker openPicker = new FileOpenPicker(); openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; openPicker.FileTypeFilter.Add(".png"); openPicker.FileTypeFilter.Add(".jpg"); openPicker.FileTypeFilter.Add(".bmp"); openPicker.FileTypeFilter.Add(".gif"); openPicker.ContinuationData["Operation"] = "img"; StorageFile file = await openPicker.PickSingleFileAsync(); if (file != null) { ClipHeadGrid.Visibility = Visibility.Visible; BackOpacityGrid.Visibility = Visibility.Visible; SoftwareBitmap sb = null; using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read)) { // Create the decoder from the stream BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); // Get the SoftwareBitmap representation of the file SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); sb = softwareBitmap; // return softwareBitmap; } SoftwareBitmapSource source = new SoftwareBitmapSource(); await source.SetBitmapAsync(sb); headImage.Source = source; } } else { var msgPopup = new Data.loginControl("您还没有登录 不能上传头像哦~"); msgPopup.LeftClick += (s, c) => { Frame rootFrame = Window.Current.Content as Frame; rootFrame.Navigate(typeof(LoginPage)); }; msgPopup.RightClick += (s, c) => { new MessageDialog("您可以先去社区逛一逛~"); }; msgPopup.ShowWIndow(); } } catch { var msgPopup = new Data.loginControl("您还没有登录 不能上传头像哦~"); msgPopup.LeftClick += (s, c) => { Frame rootFrame = Window.Current.Content as Frame; rootFrame.Navigate(typeof(LoginPage)); }; msgPopup.RightClick += (s, c) => { new MessageDialog("您可以先去社区逛一逛~"); }; msgPopup.ShowWIndow(); } }
public static async Task<SoftwareBitmapSource> ImagePathToSoftwareBitmapSource(string path) { var file = await StorageHelper.TryGetFileAsync(path); var bitmap = await StorageFileToSoftwareBitmap(file); if (bitmap == null) return null; var source = new SoftwareBitmapSource(); await source.SetBitmapAsync(bitmap); return source; }
private async void InitializeCameraAsync() { sbSource = new SoftwareBitmapSource(); receviebitMap = new SoftwareBitmap(BitmapPixelFormat.Bgra8, 240, 180, 0); buffer = new Windows.Storage.Streams.Buffer((uint)(240 * 180 * 8)); /* stream client close this */ imageElement1.Source = sbSource; streamSocketSrv = new StreamSocketListenerServer(); await streamSocketSrv.start(serverip, "22343"); streamSocketClient = new StreamSocketClient(); textBox.Text = clientip; }
private async void LoadPortraitButton_Click(object sender, RoutedEventArgs e) { portraitStream = photoStream; portraitBitmap = photoBitmap; portraitBitmapSource = photoBitmapSource; PortraitPhoto.Source = portraitBitmapSource; portraitPath = await StorageAPI.SavePhoto(portraitStream, "Portrait"); }
public async Task TakePhotoAsync(Action<SoftwareBitmapSource> callback) { //kada uslika postaviti svoj stream Slika = new InMemoryRandomAccessStream(); try { //konvertovati uslikano u Software bitmap da se moze prikazati u image kontroli await MediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateBmp(), Slika); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(Slika); SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync(); SoftwareBitmap softwareBitmapBGR8 = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); SlikaBitmap = new SoftwareBitmapSource(); await SlikaBitmap.SetBitmapAsync(softwareBitmapBGR8); callback(SlikaBitmap); } catch (Exception ex) { Debug.WriteLine("Exception when taking a photo: {0}", ex.ToString()); } }
private async Task<OcrResultDisplay> ProcessImage(StorageFile file) { SoftwareBitmap bitmap; ImageSource source; using (var imgStream = await file.OpenAsync(FileAccessMode.Read)) { var decoder = await BitmapDecoder.CreateAsync(imgStream); bitmap = await decoder.GetSoftwareBitmapAsync(); } if (bitmap == null) { source = new BitmapImage(); return new OcrResultDisplay { OcrString = "No text found.\n", OcrImage = source }; } OcrEngine engine = OcrEngine.TryCreateFromLanguage(new Windows.Globalization.Language("en")); OcrResult result = await engine.RecognizeAsync(bitmap); StringBuilder sb = new StringBuilder(); if (result.Lines == null) { source = new SoftwareBitmapSource(); bitmap = SoftwareBitmap.Convert(bitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); await ((SoftwareBitmapSource)source).SetBitmapAsync(bitmap); return new OcrResultDisplay { OcrString = "No text found.\n", OcrImage = source }; } foreach (var line in result.Lines) { foreach (var word in line.Words) { sb.Append(word.Text + " "); } sb.AppendLine(); } source = new SoftwareBitmapSource(); bitmap = SoftwareBitmap.Convert(bitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); await ((SoftwareBitmapSource)source).SetBitmapAsync(bitmap); return new OcrResultDisplay { OcrString = sb.ToString(), OcrImage = source }; }