private async void OnImageUrlChanged() { if (ImageUrl == null) { return; } var rass = RandomAccessStreamReference.CreateFromUri(new Uri(ImageUrl, UriKind.Absolute)); IRandomAccessStream stream = await rass.OpenReadAsync(); var decoder = await BitmapDecoder.CreateAsync(stream); Rect bounds = Window.Current.Bounds; //WriteableBitmap bmp = new WriteableBitmap((int)bounds.Width, (int)bounds.Height); var displayWidth = Math.Min(decoder.PixelWidth, bounds.Width); var displayHeight = Math.Min(decoder.PixelHeight, bounds.Height); WriteableBitmap bmp = new WriteableBitmap((int)displayWidth, (int)displayHeight); stream.Seek(0); //var blurFilter = new BlurFilter(60); using (var source = new RandomAccessStreamImageSource(stream)) using (var blurFilter = new LensBlurEffect(source, new LensBlurPredefinedKernel(LensBlurPredefinedKernelShape.Circle, 20))) //using (var filterEffect = new FilterEffect(source) { Filters = new[] { blurFilter } }) using (var renderer = new WriteableBitmapRenderer(blurFilter, bmp)) { bmp = await renderer.RenderAsync(); bmp.Invalidate(); BackgroundImage.Source = bmp; } }
async void GeneratePicture() { if (rendering) return; ProgressIndicator prog = new ProgressIndicator(); prog.IsIndeterminate = true; prog.Text = "Rendering"; prog.IsVisible = true; SystemTray.SetProgressIndicator(this, prog); var bmp = new WriteableBitmap(480, 800); try { rendering = true; using (var renderer = new WriteableBitmapRenderer(manager, bmp, OutputOption.PreserveAspectRatio)) { display.Source = await renderer.RenderAsync(); } SystemTray.SetProgressIndicator(this, null); rendering = false; } finally { } }
async void pct_Completed(object sender, PhotoResult e) { if (e.TaskResult != TaskResult.OK || e.ChosenPhoto == null) return; try { // Create a source to read the image from PhotoResult stream using (var source = new StreamImageSource(e.ChosenPhoto)) { using (var effect = new PixlateEffect(source)) { _effect = effect; var target = new WriteableBitmap((int)ResultImage.ActualWidth, (int)ResultImage.ActualHeight); // Create a new renderer which outputs WriteableBitmaps using (var renderer = new WriteableBitmapRenderer(effect, target)) { // Render the image with the filter(s) await renderer.RenderAsync(); // Set the output image to Image control as a source ResultImage.Source = target; } } } } catch (Exception exception) { MessageBox.Show(exception.Message); return; } }
/// <summary> /// Applies the filter. If another processing request was scheduled /// while processing the buffer, the method will recursively call /// itself. /// </summary> protected virtual async void Render() { try { if (Source != null) { Debug.WriteLine(DebugTag + Name + ": Rendering..."); // Apply the pending changes to the filter(s) foreach (var change in Changes) { change(); } Changes.Clear(); // Render the filters first to the temporary bitmap and // copy the changes then to the preview bitmap using (var renderer = new WriteableBitmapRenderer(Effect, TmpBitmap)) { await renderer.RenderAsync(); } /* "using System.Runtime.InteropServices.WindowsRuntime" is * required for WriteableBitmap.PixelBuffer.CopyTo() and * WriteableBitmap.PixelBuffer.AsStream(). */ TmpBitmap.PixelBuffer.CopyTo(PreviewBitmap.PixelBuffer); PreviewBitmap.Invalidate(); // Force a redraw } else { Debug.WriteLine(DebugTag + Name + ": Render(): No buffer set!"); } } catch (Exception e) { Debug.WriteLine(DebugTag + Name + ": Render(): " + e.Message); } finally { switch (State) { case States.Apply: // State machine transition : Apply -> Wait State = States.Wait; break; case States.Schedule: // State machine transition: Schedule -> Apply State = States.Apply; Render(); // Apply the filter break; default: // Do nothing break; } } }
}//render available bitmap private async Task RenderAsync() { //if preview is on and rendering of the previous frame finished if (!isRendering && isPreviewing) { //flag-on isRendering = true; //render frame await bitmapRenderer.RenderAsync(); //clone frame to array await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( CoreDispatcherPriority.High, (DispatchedHandler)(() => { //if capture is on and array is not filled if (isCapturing && frameIndex < maxFrameIndex) { //clone rendered frame var newimage = currentWriteableBitmap.Clone(); //add cloned frame Array.Resize(ref frameArray, frameArray.Length + 1); frameArray[frameIndex] = newimage; //go to editing if array is filled if (frameIndex + 1 == maxFrameIndex) { Frame.Navigate(typeof(Edit), frameArray); } //copy frame to previewImage if such option is enabled if (isPreviEwenabled) { previewImage.Source = newimage; } //change frameIndex frameIndex++; frameIndexBoxRefresh(); //stop capturing if capturingmodeIsPhoto isCapturing = !capturingmodeIsPhoto; //dispose cloned image newimage = null; } //invalidate currentWriteableBitmap currentWriteableBitmap.Invalidate(); GC.Collect(); })); //flag-off isRendering = false; } }//render available frame
private void AnalyzeBitmap(Bitmap bitmap, TimeSpan time) { if (ProductDetailsPanel.IsOpen) { return; } Result result = barcodeReader.Decode( bitmap.Buffers[0].Buffer.ToArray(), (int)bitmap.Buffers[0].Pitch, // Should be width here but I haven't found a way to pass both width and stride to ZXing yet (int)bitmap.Dimensions.Height, BitmapFormat.Gray8); if (result != null && IsValidEan(result.Text)) { if (autoFocus != null) { autoFocus.BarcodeFound = true; } string barcode = result.Text; var ignore = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ShowFilteringBarcode(barcode); }); BitmapImageSource bmpImgSrc = new BitmapImageSource(bitmap); WriteableBitmapRenderer renderer = new WriteableBitmapRenderer(bmpImgSrc, bitmapWithBarcode); bitmapWithBarcode = renderer.RenderAsync().AsTask().Result; if (barcodeFilter.Update(barcode)) { Debug.WriteLine(barcode); ignore = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ProductsListBox.AddProduct(barcode, bitmapWithBarcode); bitmapWithBarcode = new WriteableBitmap(bitmapWithBarcode.PixelWidth, bitmapWithBarcode.PixelHeight); if (HintTextBlock.Visibility == Visibility.Visible) { HintTextBlock.Visibility = Visibility.Collapsed; } ShowActiveBarcode(barcode); }); } } else { if (autoFocus != null) { autoFocus.BarcodeFound = false; } } }
/// <summary> /// Renders a writeable bitmap preview of the given frame. /// </summary> /// <param name="frame">Frame to render.</param> /// <param name="size">Preview size in pixels.</param> /// <returns>Rendered frame preview.</returns> public static async Task <WriteableBitmap> RenderPreviewAsync(Frame frame, Windows.Foundation.Size size) { using (var bitmap = new Bitmap(frame.Dimensions, Internal.Utilities.FrameFormatToColorMode(frame.Format), frame.Pitch, frame.Buffer.AsBuffer())) using (var source = new BitmapImageSource(bitmap)) using (var renderer = new WriteableBitmapRenderer(source, new WriteableBitmap((int)size.Width, (int)size.Height), OutputOption.Stretch)) { return(await renderer.RenderAsync()); } }
public async static Task <WriteableBitmap> Render(WriteableBitmap actualImage, List <IFilter> filters) { var bitmap = actualImage.AsBitmap(); BitmapImageSource bitmapSource = new BitmapImageSource(bitmap); FilterEffect effects = new FilterEffect(bitmapSource); effects.Filters = filters; WriteableBitmapRenderer renderer = new WriteableBitmapRenderer(effects, actualImage); return(await renderer.RenderAsync()); }
protected override async void Render() { try { if (Source != null) { Debug.WriteLine(DebugTag + Name + ": Rendering..."); foreach (var change in Changes) { change(); } Changes.Clear(); _hdrEffect.Source = Source; using (var renderer = new WriteableBitmapRenderer(_hdrEffect, TmpBitmap)) { await renderer.RenderAsync(); } TmpBitmap.PixelBuffer.CopyTo(PreviewBitmap.PixelBuffer); PreviewBitmap.Invalidate(); // Force a redraw } else { Debug.WriteLine(DebugTag + Name + ": Render(): No buffer set!"); } } catch (Exception e) { Debug.WriteLine(DebugTag + Name + ": Render(): " + e.Message); } finally { switch (State) { case States.Apply: State = States.Wait; break; case States.Schedule: State = States.Apply; Render(); break; default: break; } } }
/// <summary> /// Applies the filter. If another processing request was scheduled /// while processing the buffer, the method will recursively call /// itself. /// </summary> protected async void Render() { try { if (_source != null) { // Apply the pending changes to the filter(s) foreach (var change in _changes) { change(); } _changes.Clear(); // Render the filters first to the temporary bitmap and // copy the changes then to the preview bitmap using (WriteableBitmapRenderer renderer = new WriteableBitmapRenderer(_effect, _tmpBitmap)) { await renderer.RenderAsync(); } _tmpBitmap.Pixels.CopyTo(_previewBitmap.Pixels, 0); _previewBitmap.Invalidate(); // Force a redraw } else { System.Diagnostics.Debug.WriteLine( "AbstractFilter.ApplyFilter(): No buffer set!"); } } catch (Exception) { } finally { switch (State) { case States.Apply: // State machine transition : Apply -> Wait State = States.Wait; break; case States.Schedule: // State machine transition: Schedule -> Apply State = States.Apply; Render(); // Apply the filter break; default: // Do nothing break; } } }
async void PreviewFrameAvailable(IImageSize imageSize) { if (!_Ready || _Rendering || _Done) { return; } _Rendering = true; await _Render.RenderAsync(); Utilities.Dispatch(() => { _Image.Invalidate(); }); if (_Controller.FocusControl.Supported) { if ((_Controller.FocusControl.FocusState != MediaCaptureFocusState.Searching) && (_Controller.FocusControl.FocusState != MediaCaptureFocusState.Focused)) { _Controller.FocusControl.FocusAsync(); } } if (!_Controller.FocusControl.Supported || _Controller.FocusControl.FocusState == MediaCaptureFocusState.Focused) { // extract codes if ((_CodesFound != null) || (_DataFound != null)) { if (_Controller.FocusControl.FocusState == MediaCaptureFocusState.Focused) { if (_Width == 0) { _Width = _Image.PixelWidth; } if (_Height == 0) { _Height = _Image.PixelHeight; } AddRemoveData(_Image.PixelBuffer.ToArray()); //if (_Threads < _MaxThreads) //{ // _Threads++; // var data = _Image.PixelBuffer.ToArray(); // int width = _Image.PixelWidth, height = _Image.PixelHeight; // Task.Run(async () => FindCodes(data, width, height)); //} } } } _Rendering = false; }
public async Task RenderBitmapAsync(WriteableBitmap bitmap) { using (FilterEffect effect = new FilterEffect(ImageSource) { Filters = _filters }) using (WriteableBitmapRenderer renderer = new WriteableBitmapRenderer(effect, bitmap)) { await renderer.RenderAsync(); bitmap.Invalidate(); } }
public async static Task<WriteableBitmap> Render(WriteableBitmap actualImage, List<IFilter> filters) { var bitmap = actualImage.AsBitmap(); BitmapImageSource bitmapSource = new BitmapImageSource(bitmap); FilterEffect effects = new FilterEffect(bitmapSource); effects.Filters = filters; WriteableBitmapRenderer renderer = new WriteableBitmapRenderer(effects, actualImage); return await renderer.RenderAsync(); }
private async Task ColorizeImageInternalAsync(/*Lumia.Imaging.*/ IImageProvider inputImage, WriteableBitmap output) { using (var colorizationEffect = new ColorizationEffect(inputImage, new global::Windows.UI.Color() { R = 255, G = 0, B = 255 }, 1.0, 1.0)) // Create effect with the source stream using (var renderer = new WriteableBitmapRenderer(colorizationEffect, output)) { await renderer.RenderAsync(); output.Invalidate(); } }
protected override async void Render() { try { if (Source != null) { Debug.WriteLine(DebugTag + Name + ": Rendering..."); foreach (var change in Changes) { change(); } Changes.Clear(); _hdrEffect.Source = Source; using (var renderer = new WriteableBitmapRenderer(_hdrEffect, TmpBitmap)) { await renderer.RenderAsync(); } TmpBitmap.PixelBuffer.CopyTo(PreviewBitmap.PixelBuffer); PreviewBitmap.Invalidate(); // Force a redraw } else { Debug.WriteLine(DebugTag + Name + ": Render(): No buffer set!"); } } catch (Exception e) { Debug.WriteLine(DebugTag + Name + ": Render(): " + e.Message); } finally { switch (State) { case States.Apply: State = States.Wait; break; case States.Schedule: State = States.Apply; Render(); break; default: break; } } }
public async Task applyFilter(byte[] imageData, WriteableBitmap processedBitmap, List<IFilter> _components) { MemoryStream ms = new MemoryStream(imageData); var source = new StreamImageSource(ms); var effect = new FilterEffect(source); var renderer = new WriteableBitmapRenderer(effect, processedBitmap); var filters = new List<IFilter>(); filters = _components; effect.Filters = filters; await renderer.RenderAsync(); processedBitmap.Invalidate(); }
private async Task ApplyOriginalAsync() { OriginalBitmap = new WriteableBitmap(OriginalBitmap.PixelWidth, OriginalBitmap.PixelHeight); using (FilterEffect effect = new FilterEffect(ImageSource) { Filters = _filters }) using (WriteableBitmapRenderer renderer = new WriteableBitmapRenderer(effect, OriginalBitmap)) { await renderer.RenderAsync(); OriginalBitmap.Invalidate(); } }
/// <summary> /// Renders current image with applied filters to the given bitmap. /// </summary> /// <param name="bitmap">Bitmap to render to</param> public async Task RenderBitmapAsync(WriteableBitmap bitmap) { using (var source = new BufferImageSource(_buffer)) using (var effect = new FilterEffect(source) { Filters = _components }) using (var renderer = new WriteableBitmapRenderer(effect, bitmap)) { await renderer.RenderAsync(); bitmap.Invalidate(); } }
public static async Task <WriteableBitmap> ApplyStampThreshold(WriteableBitmap imgSource, double threshold) { var source = new BitmapImageSource(imgSource.AsBitmap()); var effect = new Lumia.Imaging.Artistic.StampEffect(source, 0, threshold); var stampImage = new WriteableBitmap(imgSource.PixelWidth, imgSource.PixelHeight); using (var renderer = new WriteableBitmapRenderer(effect, stampImage)) { // Generate the gray image await renderer.RenderAsync(); } return(stampImage); }
public static async Task <WriteableBitmap> ApplyGaussianBlur(WriteableBitmap imgSource, int kernelS) { BitmapImageSource source = new BitmapImageSource(imgSource.AsBitmap()); BlurEffect effect = new BlurEffect(source, kernelS); WriteableBitmap blurredImage = new WriteableBitmap(imgSource.PixelWidth, imgSource.PixelHeight); using (var renderer = new WriteableBitmapRenderer(effect, blurredImage)) { // Generate the gray image await renderer.RenderAsync(); } return(blurredImage); }
/// <summary> /// Apply the chosen filter(s) /// </summary> /// <param name="sampleEffect"></param> public async Task <WriteableBitmap> ApplyBasicFilter(List <IFilter> sampleEffect) { if (App.ChosenPhoto == null || _rendering) { return(null); } _rendering = true; if (IsRenderingChanged != null) { IsRenderingChanged(this, true); } var props = await App.ChosenPhoto.Properties.GetImagePropertiesAsync(); var target = new WriteableBitmap((int)props.Width, (int)props.Height); try { // Create a source to read the image from PhotoResult stream using (var source = new StorageFileImageSource(App.ChosenPhoto)) using (var filters = new FilterEffect(source)) { filters.Filters = sampleEffect.ToArray(); // Create a new renderer which outputs WriteableBitmaps using (var renderer = new WriteableBitmapRenderer(filters, target)) { // Render the image with the filter await renderer.RenderAsync(); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } _rendering = false; if (IsRenderingChanged != null) { IsRenderingChanged(this, false); } return(target); }
private async void AttemptUpdatePreviewAsync() { if (!Processing) { Processing = true; Model.OriginalImage.Position = 0; using (var source = new StreamImageSource(Model.OriginalImage)) using (var segmenter = new InteractiveForegroundSegmenter(source)) using (var annotationsSource = new BitmapImageSource(Model.AnnotationsBitmap)) { segmenter.Quality = 0.5; segmenter.AnnotationsSource = annotationsSource; var foregroundColor = Model.ForegroundBrush.Color; var backgroundColor = Model.BackgroundBrush.Color; segmenter.ForegroundColor = Windows.UI.Color.FromArgb(foregroundColor.A, foregroundColor.R, foregroundColor.G, foregroundColor.B); segmenter.BackgroundColor = Windows.UI.Color.FromArgb(backgroundColor.A, backgroundColor.R, backgroundColor.G, backgroundColor.B); do { _processingPending = false; var previewBitmap = new WriteableBitmap((int)Model.AnnotationsBitmap.Dimensions.Width, (int)Model.AnnotationsBitmap.Dimensions.Height); using (var effect = new LensBlurEffect(source, new LensBlurPredefinedKernel(Shape, (uint)SizeSlider.Value))) using (var renderer = new WriteableBitmapRenderer(effect, previewBitmap)) { effect.KernelMap = segmenter; await renderer.RenderAsync(); PreviewImage.Source = previewBitmap; previewBitmap.Invalidate(); } }while (_processingPending); } Processing = false; } else { _processingPending = true; } }
private async Task <bool> ApplyFilterAsync(StorageFile file) { // Open a stream for the selected file. IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read); string errorMessage = null; try { // Show thumbnail of original image. _thumbnailImageBitmap.SetSource(fileStream); OriginalImage.Source = _thumbnailImageBitmap; // Rewind stream to start. fileStream.Seek(0); // A cartoon effect is initialized with selected image stream as source. var imageStream = new RandomAccessStreamImageSource(fileStream); _cartoonEffect = new FilterEffect(imageStream); // Add the cartoon filter as the only filter for the effect. var cartoonFilter = new CartoonFilter(); _cartoonEffect.Filters = new[] { cartoonFilter }; // Render the image to a WriteableBitmap. var renderer = new WriteableBitmapRenderer(_cartoonEffect, _cartoonImageBitmap); _cartoonImageBitmap = await renderer.RenderAsync(); _cartoonImageBitmap.Invalidate(); // Set the rendered image as source for the cartoon image control. CartoonImage.Source = _cartoonImageBitmap; } catch (Exception exception) { errorMessage = exception.Message; } if (!string.IsNullOrEmpty(errorMessage)) { var dialog = new MessageDialog(errorMessage); await dialog.ShowAsync(); return(false); } return(true); }
private async Task ApplyFilter(ImageFilter imageFilter, Image image) { FilterEffect effect = new FilterEffect(new BitmapImageSource(ImageToFilter.AsBitmap())); effect.Filters = new IFilter[] { imageFilter.Filter }; WriteableBitmap temporaryImage = new WriteableBitmap(MainPage.ImageToFilter); WriteableBitmapRenderer renderer = new WriteableBitmapRenderer(effect, temporaryImage); await renderer.RenderAsync(); image.Source = temporaryImage; // Here we create a new EditingSession based on our selected image and add the selected filter to it // After the picture gets rendered to our delivered image //editingSession = new EditingSession(ImageToFilter.AsBitmap()); //editingSession.AddFilter(imageFilter.Filter); //await editingSession.RenderToImageAsync(image, OutputOption.PreserveAspectRatio); }
async void FilterView_Loaded(object sender, RoutedEventArgs e) { // To edit a picture with the Nokia Imaging SDK we need a FilterEffect // Such a filter session is based on an image and one or more filters // Here we create a new FilterEffect that is based on our on the MainPage selected image FilterEffect effect = new FilterEffect(new BitmapImageSource(MainPage.ImageToFilter.AsBitmap())); // Add the filter we want to offer to our users to the list // You can find an overview of mor filters here: http://developer.nokia.com/Resources/Library/Lumia/#!nokia-imaging-sdk.html filterList = new List<ImageFilter>(); filterList.Add(new ImageFilter("Cartoon", new CartoonFilter(true))); filterList.Add(new ImageFilter("Antique", new AntiqueFilter())); filterList.Add(new ImageFilter("Color Boost", new ColorBoostFilter(2))); filterList.Add(new ImageFilter("Gray Scale", new GrayscaleFilter())); filterList.Add(new ImageFilter("Negative", new NegativeFilter())); filterList.Add(new ImageFilter("Sktech", new SketchFilter(SketchMode.Color))); filterList.Add(new ImageFilter("Mirror", new MirrorFilter())); // Here we add a new PivotItem for every filter we want to use // So the user can flip through all offered filters in the PivotControl of this page foreach (ImageFilter imageFilter in filterList) { // Create a new Image that we can add to each PivotItem later as a preview of the filter Image pivotItemImage = new Image(); pivotItemImage.Width = 400; pivotItemImage.Height = 400; // Create the PivotItem that we want to add and set its content to the preview image we created above PivotItem pivotItem = new PivotItem(); pivotItem.Header = imageFilter.Name; pivotItem.Content = pivotItemImage; // Now we add the created PivotItem to the PivotControl on this page FilterPivot.Items.Add(pivotItem); // Add the current filter effect.Filters = new IFilter[] { imageFilter.Filter }; // Last we need to render the preview image WriteableBitmap temporaryImage = new WriteableBitmap(MainPage.ImageToFilter); WriteableBitmapRenderer renderer = new WriteableBitmapRenderer(effect, temporaryImage); await renderer.RenderAsync(); pivotItemImage.Source = temporaryImage; } }
async void FilterView_Loaded(object sender, RoutedEventArgs e) { // To edit a picture with the Nokia Imaging SDK we need a FilterEffect // Such a filter session is based on an image and one or more filters // Here we create a new FilterEffect that is based on our on the MainPage selected image FilterEffect effect = new FilterEffect(new BitmapImageSource(MainPage.ImageToFilter.AsBitmap())); // Add the filter we want to offer to our users to the list // You can find an overview of mor filters here: http://developer.nokia.com/Resources/Library/Lumia/#!nokia-imaging-sdk.html filterList = new List <ImageFilter>(); filterList.Add(new ImageFilter("Cartoon", new CartoonFilter(true))); filterList.Add(new ImageFilter("Antique", new AntiqueFilter())); filterList.Add(new ImageFilter("Color Boost", new ColorBoostFilter(2))); filterList.Add(new ImageFilter("Gray Scale", new GrayscaleFilter())); filterList.Add(new ImageFilter("Negative", new NegativeFilter())); filterList.Add(new ImageFilter("Sktech", new SketchFilter(SketchMode.Color))); filterList.Add(new ImageFilter("Mirror", new MirrorFilter())); // Here we add a new PivotItem for every filter we want to use // So the user can flip through all offered filters in the PivotControl of this page foreach (ImageFilter imageFilter in filterList) { // Create a new Image that we can add to each PivotItem later as a preview of the filter Image pivotItemImage = new Image(); pivotItemImage.Width = 400; pivotItemImage.Height = 400; // Create the PivotItem that we want to add and set its content to the preview image we created above PivotItem pivotItem = new PivotItem(); pivotItem.Header = imageFilter.Name; pivotItem.Content = pivotItemImage; // Now we add the created PivotItem to the PivotControl on this page FilterPivot.Items.Add(pivotItem); // Add the current filter effect.Filters = new IFilter[] { imageFilter.Filter }; // Last we need to render the preview image WriteableBitmap temporaryImage = new WriteableBitmap(MainPage.ImageToFilter); WriteableBitmapRenderer renderer = new WriteableBitmapRenderer(effect, temporaryImage); await renderer.RenderAsync(); pivotItemImage.Source = temporaryImage; } }
private async Task ApplyFilter(ImageFilter imageFilter, Image image) { FilterEffect effect = new FilterEffect(new BitmapImageSource(ImageToFilter.AsBitmap())); effect.Filters = new IFilter[] { imageFilter.Filter }; WriteableBitmap temporaryImage = new WriteableBitmap(MainPage.ImageToFilter); WriteableBitmapRenderer renderer = new WriteableBitmapRenderer(effect, temporaryImage); await renderer.RenderAsync(); image.Source = temporaryImage; // Here we create a new EditingSession based on our selected image and add the selected filter to it // After the picture gets rendered to our delivered image //editingSession = new EditingSession(ImageToFilter.AsBitmap()); //editingSession.AddFilter(imageFilter.Filter); //await editingSession.RenderToImageAsync(image, OutputOption.PreserveAspectRatio); }
private async void OnPreviewFrameAvailable(IImageSize args) { if (!_initialized || _isRendering) { return; } _isRendering = true; await Task.Run(() => { _writeableBitmap.Invalidate(); }); await _writeableBitmapRenderer.RenderAsync(); await Task.Run(() => { Deocode(_writeableBitmap.PixelBuffer.ToArray(), BitmapFormat.Unknown); }); _isRendering = false; }
async public static Task<WriteableBitmap> Render(List<IFilter> filterList, MemoryStream inputStream) { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(inputStream); WriteableBitmap outputBitmap = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight); inputStream.Position = 0; // An effect is initialized with selected image stream as source. var imageStream = new StreamImageSource(inputStream); FilterEffect _effect = new FilterEffect(imageStream); _effect.Filters = filterList; // Render the image to a WriteableBitmap. var renderer = new WriteableBitmapRenderer(_effect, outputBitmap, OutputOption.Stretch); outputBitmap = await renderer.RenderAsync(); return outputBitmap; }
private async void OnPreviewFrameAvailable(IImageSize imageSize) { if (!_isRendering) { _isRendering = true; await _writeableBitmapRenderer.RenderAsync(); await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( CoreDispatcherPriority.High, () => { int bufferSize = _writeableBitmap.PixelWidth *_writeableBitmap.PixelHeight * 4; if (_buffer == null || _buffer.Length != bufferSize) { _buffer = new byte[bufferSize]; } IBuffer pixelBuffer = _writeableBitmap.PixelBuffer; pixelBuffer.CopyTo(_buffer); GCHandle handle = GCHandle.Alloc(_buffer, GCHandleType.Pinned); using ( Mat m = new Mat(_writeableBitmap.PixelHeight, _writeableBitmap.PixelWidth, DepthType.Cv8U, 4, handle.AddrOfPinnedObject(), _writeableBitmap.PixelWidth * 4)) using (Mat gray = new Mat()) using (Mat canny = new Mat()) { CvInvoke.CvtColor(m, gray, ColorConversion.Bgr2Gray); CvInvoke.Canny(gray, canny, 40, 60); CvInvoke.CvtColor(canny, m, ColorConversion.Gray2Bgra); } handle.Free(); using (Stream s = pixelBuffer.AsStream()) { s.Write(_buffer, 0, _buffer.Length); } _writeableBitmap.Invalidate(); }); _isRendering = false; } }
private async Task DoRender(IReadOnlyList <IImageProvider> imageProviders, int animationIndex, bool renderBackground = false) { if (_onScreenImageProviders[animationIndex] != null) { int imageWidth = imageProviders == _unalignedImageProviders ? _unalignedImageWidth : _alignedImageWidth; int imageHeight = imageProviders == _unalignedImageProviders ? _unalignedImageHeight : _alignedImageHeight; if (_foregroundBitmap == null || _foregroundBitmap.PixelWidth != imageWidth || _foregroundBitmap.PixelHeight != imageHeight) { _foregroundBitmap = new WriteableBitmap(imageWidth, imageHeight); } using (WriteableBitmapRenderer writeableBitmapRenderer = new WriteableBitmapRenderer(imageProviders[animationIndex], _foregroundBitmap)) { _foregroundBitmap = await writeableBitmapRenderer.RenderAsync(); } if (renderBackground) { if (_backgroundBitmap == null || _backgroundBitmap.PixelWidth != imageWidth || _backgroundBitmap.PixelHeight != imageHeight) { _backgroundBitmap = new WriteableBitmap(imageWidth, imageHeight); } using (WriteableBitmapRenderer writeableBitmapRenderer = new WriteableBitmapRenderer(imageProviders[0], _backgroundBitmap)) { _backgroundBitmap = await writeableBitmapRenderer.RenderAsync(); } } await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { _foregroundBitmap.Invalidate(); ImageElement.Source = _foregroundBitmap; if (renderBackground) { _backgroundBitmap.Invalidate(); ImageElementBackground.Source = _backgroundBitmap; } }); } }
/// <summary> /// Render a frame with the selected filter /// </summary> private async void OnPreviewFrameAvailable(IImageSize args) { // Prevent multiple rendering attempts at once if (Initialized && !_isRendering) { _isRendering = true; // User changed the filter, let's update it before rendering // Render the image with the filter await _writeableBitmapRenderer.RenderAsync(); await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () => { TestWritableBitmap = _writeableBitmap; Status = "Trying to do something .. "; //System.Drawing.Bitmap temp = (System.Drawing.Bitmap)_writeableBitmap; //try //{ // frameCounter++; // if(frameCounter>10) // { // cards = recognizer.Recognize(temp); // frameCounter = 0; // } //} //catch //{ } _writeableBitmap.Invalidate(); Status = "Done Something"; }); _isRendering = false; } }
private async Task RenderPlainPhoto() { using (var source = new StreamImageSource(App.ChosenPhoto)) { // Create a target where the filtered image will be rendered to var target = new WriteableBitmap((int)ImageControl.ActualWidth, (int)ImageControl.ActualHeight); // Create a new renderer which outputs WriteableBitmaps using (var renderer = new WriteableBitmapRenderer(source, target)) { // Render the image with the filter(s) await renderer.RenderAsync(); // Set the output image to Image control as a source ImageControl.Source = target; App.ChosenPhoto.Position = 0; } } }
private async Task Render() { if (!_rendering && !_stop) { _rendering = true; // Render camera preview frame to screen _writeableBitmapRenderer.Source = _cameraPreviewImageSource; _writeableBitmapRenderer.WriteableBitmap = _writeableBitmap; await _writeableBitmapRenderer.RenderAsync(); await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( CoreDispatcherPriority.High, () => { _writeableBitmap.Invalidate(); }); // Write camera preview frame to file if capturing if (_capturing) { if (_sequenceIndex < 20) { _jpegRenderer.Source = _cameraPreviewImageSource; IBuffer jpg = await _jpegRenderer.RenderAsync(); await Save(jpg, _sequenceIndex ++); } else { StartStopCapture(); } } _rendering = false; } if (_stop) { _capturing = false; _cameraPreviewImageSource.Dispose(); _writeableBitmapRenderer.Dispose(); _jpegRenderer.Dispose(); } }
private async void OnPreviewFrameAvailable(IImageSize args) { if (!_initialized || _isRendering) { return; } _isRendering = true; await Dispatcher.RunAsync( CoreDispatcherPriority.High, () => { _writeableBitmap.Invalidate(); }); await _writeableBitmapRenderer.RenderAsync(); Dispatcher.RunAsync( CoreDispatcherPriority.High, () => { Deocode(_writeableBitmap.PixelBuffer.ToArray(), BitmapFormat.Unknown); }); //FPS calculation var now = DateTime.Now; var delta = now - _lastFrame; _lastFrame = now; var fps = 1000.0 / delta.TotalMilliseconds; await Dispatcher.RunAsync( CoreDispatcherPriority.High, () => { FpsCounter.Text = String.Format("FPS: {0:0.0}", fps); }); _isRendering = false; }
private async void RenderLenseContentAsync(Point center) { _lastLenseCenterForRendering = center; if (!_renderingLenseContent) { _renderingLenseContent = true; HighResolutionCropImage.Visibility = Visibility.Collapsed; do { center = _lastLenseCenterForRendering; // Scale between the rendered image element and the bitmap displayed in it var previewToHighResolutionCropScale = _info.ImageSize.Width / PreviewImage.ActualWidth; var screenScaleFactor = App.Current.Host.Content.ScaleFactor / 100.0; // Find crop area top left coordinate in the actual high resolution image var topLeftX = center.X * previewToHighResolutionCropScale - LenseContent.Width / 2 * screenScaleFactor / DIGITAL_MAGNIFICATION; var topLeftY = center.Y * previewToHighResolutionCropScale - LenseContent.Height / 2 * screenScaleFactor / DIGITAL_MAGNIFICATION; // Find crop area bottom right coordinate in the actual high resolution image var bottomRightX = center.X * previewToHighResolutionCropScale + LenseContent.Width / 2 * screenScaleFactor / DIGITAL_MAGNIFICATION; var bottomRightY = center.Y * previewToHighResolutionCropScale + LenseContent.Height / 2 * screenScaleFactor / DIGITAL_MAGNIFICATION; var topLeft = new Windows.Foundation.Point(topLeftX, topLeftY); var bottomRight = new Windows.Foundation.Point(bottomRightX, bottomRightY); _reframingFilter.ReframingArea = new Windows.Foundation.Rect(topLeft, bottomRight); await _renderer.RenderAsync(); } while (_lastLenseCenterForRendering != center); _highResolutionCropBitmap.Invalidate(); HighResolutionCropImage.Visibility = Visibility.Visible; _renderingLenseContent = false; } }
async void GeneratePicture() { var bmp = new WriteableBitmap(480, 800); try { rendering = true; using (var effect = new CustomEffect.SmoothBorder(picture, 5)) using (var renderer = new WriteableBitmapRenderer(effect, bmp, OutputOption.PreserveAspectRatio)) { display.Source = await renderer.RenderAsync(); } } finally { rendering = false; } }
/// <summary> /// Render a photo without any filters /// </summary> /// <param name="imageControl"></param> /// <returns></returns> public async Task RenderPlainPhoto(Image imageControl) { using (var source = new StorageFileImageSource(App.ChosenPhoto)) { var props = await App.ChosenPhoto.Properties.GetImagePropertiesAsync(); // Create a target where the filtered image will be rendered to var target = new WriteableBitmap((int)props.Width, (int)props.Height); // Create a new renderer which outputs WriteableBitmaps using (var renderer = new WriteableBitmapRenderer(source, target)) { // Render the image with the filter(s) await renderer.RenderAsync(); // Set the output image to Image control as a source imageControl.Source = target; } } }
private async Task Render() { // On AFFICHE 1 image après l'autre, on ignore celles qui arrivent entre temps if (await _semRender.WaitAsync(0) == true) { try { byte[] pixelsArray = null; // Render camera preview frame to screen _writeableBitmapRenderer.WriteableBitmap = _writeableBitmap; await _writeableBitmapRenderer.RenderAsync(); await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( CoreDispatcherPriority.High, () => { // On clone pour ne pas être lié au thread de l'UI dans le scan de code barre pixelsArray = _writeableBitmap.PixelBuffer.ToArray(); _writeableBitmap.Invalidate(); }); if (_capturing) { // On SCANNE 1 image à la fois on ignore celles qui arrivent entre temps if (await _semScan.WaitAsync(0) == true) { // On n'attend pas la fin... await Task.Run(() => ScanImage(pixelsArray)); } } } catch (Exception ex) { OnError(ex); } finally { _semRender.Release(); } } }
/// <summary> /// For the given bitmap renders filtered thumbnails for each filter in given list and populates /// the given wrap panel with the them. /// /// For quick rendering, renders 10 thumbnails synchronously and then releases the calling thread. /// </summary> /// <param name="bitmap">Source bitmap to be filtered</param> /// <param name="side">Side length of square thumbnails to be generated</param> /// <param name="list">List of filters to be used, one per each thumbnail to be generated</param> /// <param name="panel">Wrap panel to be populated with the generated thumbnails</param> private async Task RenderThumbnailsAsync(Bitmap bitmap, int side, List <FilterModel> list, WrapPanel panel) { using (var source = new BitmapImageSource(bitmap)) using (var effect = new FilterEffect(source)) { foreach (FilterModel filter in list) { effect.Filters = filter.Components; WriteableBitmap writeableBitmap = new WriteableBitmap(side, side); using (var renderer = new WriteableBitmapRenderer(effect, writeableBitmap)) { await renderer.RenderAsync(); writeableBitmap.Invalidate(); var photoThumbnail = new PhotoThumbnail() { Bitmap = writeableBitmap, Text = filter.Name, Width = side, Margin = new Thickness(6) }; FilterModel tempFilter = filter; photoThumbnail.Tap += (object sender, System.Windows.Input.GestureEventArgs e) => { App.PhotoModel.ApplyFilter(tempFilter); App.PhotoModel.Dirty = true; NavigationService.GoBack(); }; panel.Children.Add(photoThumbnail); } } } }
async void GeneratePicture() { if (picture == null || rendering) return; var bmp = new WriteableBitmap(480, 800); try { rendering = true; using (var effect = new CustomEffect.GrayscaleToAlphaEffect(picture, alpha)) using (var renderer = new WriteableBitmapRenderer(effect, bmp)) { display.Source = await renderer.RenderAsync(); } } finally { rendering = false; } }
private async void PickImageCallback(object sender, PhotoResult e) { if (e.TaskResult != TaskResult.OK || e.ChosenPhoto == null) return; try { // Show thumbnail of original image. _thumbnailImageBitmap.SetSource(e.ChosenPhoto); OriginalImage.Source = _thumbnailImageBitmap; // Rewind stream to start. e.ChosenPhoto.Position = 0; // A cartoon effect is initialized with selected image stream as source. var imageStream = new StreamImageSource(e.ChosenPhoto); _cartoonEffect = new FilterEffect(imageStream); // Add the cartoon filter as the only filter for the effect. var cartoonFilter = new CartoonFilter(); _cartoonEffect.Filters = new[] { cartoonFilter }; // Render the image to a WriteableBitmap. var renderer = new WriteableBitmapRenderer(_cartoonEffect, _cartoonImageBitmap); _cartoonImageBitmap = await renderer.RenderAsync(); // Set the rendered image as source for the cartoon image control. CartoonImage.Source = _cartoonImageBitmap; } catch (Exception exception) { MessageBox.Show(exception.Message); return; } SaveButton.IsEnabled = true; }
async void setInput(Stream s) { //reset stream position s.Seek(0, SeekOrigin.Begin); //create a session using (var source = new StreamImageSource(s)) using (var renderer = new WriteableBitmapRenderer(source)) { var info = await source.GetInfoAsync(); InputLR = new WriteableBitmap( (int)( info.ImageSize.Width), (int)(info.ImageSize.Height) ); renderer.WriteableBitmap = InputLR; await renderer.RenderAsync(); inputSize = new Size() { Width = info.ImageSize.Width, Height = info.ImageSize.Height }; currentPos = new Point(info.ImageSize.Width / 2, info.ImageSize.Height / 2); if (info.ImageSize.Width > info.ImageSize.Height) { currentScale = outputSize.Height / info.ImageSize.Height; } else { currentScale = outputSize.Width / info.ImageSize.Width; } currentAngle = 0.0; } saveLastPossaveLastPositionData(); brush.ImageSource = InputLR; brush.Stretch = Stretch.None; brush.AlignmentX = AlignmentX.Left; brush.AlignmentY = AlignmentY.Top; processRenderingLR(); }
private async void PickImageCallback(object sender, PhotoResult e) { if (e.TaskResult != TaskResult.OK || e.ChosenPhoto == null) return; try { // mostramos el thumbnail de la imagen original. _thumbnailImageBitmap.SetSource(e.ChosenPhoto); ImagenOriginal.Source = _thumbnailImageBitmap; e.ChosenPhoto.Position = 0; // inicializamos lo necesario para el filtro de la imagen. var imageStream = new StreamImageSource(e.ChosenPhoto); _fotoEffect = new FilterEffect(imageStream); // agregammos el filtro a la imagen. var filtro = new AntiqueFilter(); ; _fotoEffect.Filters = new[] { filtro }; // renderizamos la imagen a un WriteableBitmap. var renderer = new WriteableBitmapRenderer(_fotoEffect, _effectImageBitmap); _effectImageBitmap = await renderer.RenderAsync(); // Establecemos la imagen renderizada como fuente para el control de la imagen efecto. ImagenEfecto.Source = _effectImageBitmap; rendererefect = _effectImageBitmap; } catch (Exception exception) { MessageBox.Show(exception.Message); return; } }
async public static Task<WriteableBitmap> Render(List<String> effString, MemoryStream inputStream) { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(inputStream); WriteableBitmap outputBitmap = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight); inputStream.Position = 0; // An effect is initialized with selected image stream as source. var imageStream = new StreamImageSource(inputStream); List<IFilter> _effListTmp = new List<IFilter>(); foreach (String effStr in effString) { // Add filter _effListTmp.Add(GetIFilter(effStr)); } FilterEffect _effect = new FilterEffect(imageStream); _effect.Filters = _effListTmp; // Render the image to a WriteableBitmap. var renderer = new WriteableBitmapRenderer(_effect, outputBitmap, OutputOption.Stretch); outputBitmap = await renderer.RenderAsync(); return outputBitmap; }
async void GeneratePicture() { try { var info = await picture.GetInfoAsync(); var bmp = new WriteableBitmap((int)info.ImageSize.Width, (int)info.ImageSize.Height); rendering = true; // using (var effect = new CustomEffect.HighlightAlpha(picture,13)) using (var effect = new FilterEffect(picture) { Filters = new IFilter[] { new HighlightAlphaFilter(13) } }) using (var renderer = new WriteableBitmapRenderer(effect, bmp, OutputOption.PreserveAspectRatio)) { display.Source = await renderer.RenderAsync(); } } finally { rendering = false; } }
private async Task Render(int animationIndex, bool refreshBackground = false) { if (!_rendering) { _rendering = true; using (WriteableBitmapRenderer writeableBitmapRenderer = new WriteableBitmapRenderer(_onScreenImageProviders[animationIndex], _foregroundImage)) { ImageElement.Source = await writeableBitmapRenderer.RenderAsync(); } if (refreshBackground) { using (WriteableBitmapRenderer writeableBitmapRenderer = new WriteableBitmapRenderer(_onScreenImageProviders[0], _backgroundImage)) { ImageElementBackground.Source = await writeableBitmapRenderer.RenderAsync(); } } _rendering = false; } if (_saveAfterRender) { _saveAfterRender = false; Save(); } }
/// <summary> /// For the given bitmap renders filtered thumbnails for each filter in given list and populates /// the given wrap panel with the them. /// /// For quick rendering, renders 10 thumbnails synchronously and then releases the calling thread. /// </summary> /// <param name="bitmap">Source bitmap to be filtered</param> /// <param name="side">Side length of square thumbnails to be generated</param> /// <param name="list">List of filters to be used, one per each thumbnail to be generated</param> /// <param name="panel">Wrap panel to be populated with the generated thumbnails</param> private async Task RenderThumbnailsAsync(Bitmap bitmap, int side, List<FilterModel> list, WrapPanel panel) { using (BitmapImageSource source = new BitmapImageSource(bitmap)) using (FilterEffect effect = new FilterEffect(source)) { foreach (FilterModel filter in list) { effect.Filters = filter.Components; WriteableBitmap writeableBitmap = new WriteableBitmap(side, side); using (WriteableBitmapRenderer renderer = new WriteableBitmapRenderer(effect, writeableBitmap)) { await renderer.RenderAsync(); writeableBitmap.Invalidate(); PhotoThumbnail photoThumbnail = new PhotoThumbnail() { Bitmap = writeableBitmap, Text = filter.Name, Width = side, Margin = new Thickness(6) }; photoThumbnail.Tap += (object sender, System.Windows.Input.GestureEventArgs e) => { App.PhotoModel.ApplyFilter(filter); App.PhotoModel.Dirty = true; NavigationService.GoBack(); }; panel.Children.Add(photoThumbnail); } } } }
private async Task LoadImage(String filename) { var storageFile = await KnownFolders.SavedPictures.GetFileAsync(filename); var storageFileImageSource = new StorageFileImageSource(storageFile); var asyncImageResource = storageFileImageSource as IAsyncImageResource; var imageResource = await asyncImageResource.LoadAsync(); for (uint frameIndex = 0; frameIndex < imageResource.FrameCount; frameIndex++) { imageResource.FrameIndex = frameIndex; var writeableBitmap = new WriteableBitmap((int)imageResource.ImageSize.Width, (int)imageResource.ImageSize.Height); using (var writeableBitmapRenderer = new WriteableBitmapRenderer(storageFileImageSource, writeableBitmap)) { writeableBitmapRenderer.RenderOptions = RenderOptions.Cpu; await writeableBitmapRenderer.RenderAsync(); _frames.Add(writeableBitmap); } } StartAnimation(); }
void selectPicture() { try { PhotoChooserTask task = new PhotoChooserTask(); task.Completed += async (s, res) => { if (res.TaskResult == TaskResult.OK) { if (HRImagesource != null) { HRImagesource.Dispose(); HRImagesource = null; } HRImagesource = new StreamImageSource(res.ChosenPhoto); var info = await HRImagesource.GetInfoAsync(); ImageSize = info.ImageSize; //create LR image using (var renderer = new WriteableBitmapRenderer(HRImagesource, LRImageSource)) await renderer.RenderAsync(); requestProcessing(); } }; task.Show(); } catch (Exception) { throw; } }
async private void ApplicationBarIconButton_Bench(object sender, EventArgs e) { if (currentState != STATE.WAIT || HRImagesource == null) return; try { benchResult = "BENCH RUNNING..."; IsEnabled = false; benchRuning = true; ApplicationBar.IsVisible = false; displayInfo.Visibility = Visibility.Visible; var bitmap = new WriteableBitmap((int)ImageSize.Width, (int)ImageSize.Height); int nbTest = 0; double tmin = double.PositiveInfinity; double tmax = 0; double tacc = 0; for (; nbTest < 100 && benchRuning; ++nbTest) { var t = DateTime.Now; var effect = RecipeFactory.Current.CreatePipeline(HRImagesource); using (var renderer = new WriteableBitmapRenderer(effect, bitmap)) { await renderer.RenderAsync(); } if (effect is IDisposable) (effect as IDisposable).Dispose(); var ms = DateTime.Now.Subtract(t).TotalMilliseconds; tacc += ms; if (ms < tmin) tmin = ms; if (ms > tmax) tmax = ms; benchResult = string.Format( @"BENCH RUNNING... Nb rendering = {0} TMin = {1:F} TMax = {2:F} TMean = {3:F} ImageSize = {4}x{5} ", (1 + nbTest), tmin, tmax, tacc / (1 + nbTest), (int)ImageSize.Width, (int)ImageSize.Height); } benchResult = string.Format( @"BENCH FINISHED Nb rendering = {0} TMin = {1:F} TMax = {2:F} TMean = {3:F} ImageSize = {4}x{5} ", (1 + nbTest), tmin, tmax, tacc / (1 + nbTest), (int)ImageSize.Width, (int)ImageSize.Height); } finally { benchRuning = false; IsEnabled = true; ApplicationBar.IsVisible = true; } }
/// <summary> /// Applies the filter. If another processing request was scheduled /// while processing the buffer, the method will recursively call /// itself. /// </summary> protected async void Render() { try { if (_source != null) { // Apply the pending changes to the filter(s) foreach (var change in _changes) { change(); } _changes.Clear(); // Render the filters first to the temporary bitmap and // copy the changes then to the preview bitmap using (WriteableBitmapRenderer renderer = new WriteableBitmapRenderer(_effect, _tmpBitmap)) { await renderer.RenderAsync(); } _tmpBitmap.Pixels.CopyTo(_previewBitmap.Pixels, 0); _previewBitmap.Invalidate(); // Force a redraw } else { System.Diagnostics.Debug.WriteLine( "AbstractFilter.ApplyFilter(): No buffer set!"); } } catch (Exception) { } finally { switch (State) { case States.Apply: // State machine transition : Apply -> Wait State = States.Wait; break; case States.Schedule: // State machine transition: Schedule -> Apply State = States.Apply; Render(); // Apply the filter break; default: // Do nothing break; } } }
async void processRendering() { try { if (LRImageSource == null) return; using (var source = new BitmapImageSource(LRImageSource.AsBitmap())) { var t = DateTime.Now; var effect = RecipeFactory.Current.CreatePipeline(source); using (var renderer = new WriteableBitmapRenderer(effect, bitmapTmp)) { var result = await renderer.RenderAsync(); var ms = DateTime.Now.Subtract(t).TotalMilliseconds; previewResult = string.Format( @"ImageSize = {0}x{1} t = {1:F} ", bitmapTmp.PixelWidth, bitmapTmp.PixelHeight, ms); } if (effect is IDisposable) (effect as IDisposable).Dispose(); } bitmapTmp.Invalidate(); var tmp = bitmapTmp; bitmapTmp = bitmapDisplayed; bitmapDisplayed = tmp; bitmapDisplayed.Invalidate(); displayBackgroundBrush.ImageSource = bitmapDisplayed; } catch (Exception) { } finally { processFinished(); } }
private async void AttemptUpdatePreviewAsync() { if (!Processing) { Processing = true; AdaptButtonsToState(); Model.OriginalImage.Position = 0; using (var source = new StreamImageSource(Model.OriginalImage)) using (var segmenter = new InteractiveForegroundSegmenter(source)) using (var annotationsSource = new BitmapImageSource(Model.AnnotationsBitmap)) { segmenter.Quality = 0.5; segmenter.AnnotationsSource = annotationsSource; var foregroundColor = Model.ForegroundBrush.Color; var backgroundColor = Model.BackgroundBrush.Color; segmenter.ForegroundColor = Windows.UI.Color.FromArgb(foregroundColor.A, foregroundColor.R, foregroundColor.G, foregroundColor.B); segmenter.BackgroundColor = Windows.UI.Color.FromArgb(backgroundColor.A, backgroundColor.R, backgroundColor.G, backgroundColor.B); do { _processingPending = false; var previewBitmap = new WriteableBitmap((int)Model.AnnotationsBitmap.Dimensions.Width, (int)Model.AnnotationsBitmap.Dimensions.Height); using (var effect = new LensBlurEffect(source, new LensBlurPredefinedKernel(Model.KernelShape, (uint)Model.KernelSize))) using (var renderer = new WriteableBitmapRenderer(effect, previewBitmap)) { effect.KernelMap = segmenter; try { await renderer.RenderAsync(); PreviewImage.Source = previewBitmap; previewBitmap.Invalidate(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("AttemptUpdatePreviewAsync rendering failed: " + ex.Message); } } } while (_processingPending); } Processing = false; AdaptButtonsToState(); } else { _processingPending = true; } }
/// <summary> /// Applies the filter. If another processing request was scheduled /// while processing the buffer, the method will recursively call /// itself. /// </summary> protected virtual async void Render() { try { if (_source != null) { Debug.WriteLine(DebugTag + Name + ": Rendering..."); // Apply the pending changes to the filter(s) foreach (var change in Changes) { change(); } Changes.Clear(); // Render the filters first to the temporary bitmap and // copy the changes then to the preview bitmap using (var renderer = new WriteableBitmapRenderer(_effect, _tmpBitmap)) { await renderer.RenderAsync(); } /* "using System.Runtime.InteropServices.WindowsRuntime" is * required for WriteableBitmap.PixelBuffer.CopyTo() and * WriteableBitmap.PixelBuffer.AsStream(). */ _tmpBitmap.PixelBuffer.CopyTo(_previewBitmap.PixelBuffer); _previewBitmap.Invalidate(); // Force a redraw } else { Debug.WriteLine(DebugTag + Name + ": Render(): No buffer set!"); } } catch (Exception e) { Debug.WriteLine(DebugTag + Name + ": Render(): " + e.Message); } finally { switch (State) { case States.Apply: // State machine transition : Apply -> Wait State = States.Wait; break; case States.Schedule: // State machine transition: Schedule -> Apply State = States.Apply; Render(); // Apply the filter break; default: // Do nothing break; } } }
private async void AttemptUpdatePreviewAsync() { if (!Processing) { Processing = true; do { _processingPending = false; if (Model.OriginalImage != null && ForegroundAnnotationsDrawn && BackgroundAnnotationsDrawn) { Model.OriginalImage.Position = 0; var maskBitmap = new WriteableBitmap((int)AnnotationsCanvas.ActualWidth, (int)AnnotationsCanvas.ActualHeight); var annotationsBitmap = new WriteableBitmap((int)AnnotationsCanvas.ActualWidth, (int)AnnotationsCanvas.ActualHeight); annotationsBitmap.Render(AnnotationsCanvas, new ScaleTransform { ScaleX = 1, ScaleY = 1 }); annotationsBitmap.Invalidate(); Model.OriginalImage.Position = 0; using (var source = new StreamImageSource(Model.OriginalImage)) using (var segmenter = new InteractiveForegroundSegmenter(source)) using (var renderer = new WriteableBitmapRenderer(segmenter, maskBitmap)) using (var annotationsSource = new BitmapImageSource(annotationsBitmap.AsBitmap())) { var foregroundColor = Model.ForegroundBrush.Color; var backgroundColor = Model.BackgroundBrush.Color; segmenter.ForegroundColor = Windows.UI.Color.FromArgb(foregroundColor.A, foregroundColor.R, foregroundColor.G, foregroundColor.B); segmenter.BackgroundColor = Windows.UI.Color.FromArgb(backgroundColor.A, backgroundColor.R, backgroundColor.G, backgroundColor.B); segmenter.Quality = 0.5; segmenter.AnnotationsSource = annotationsSource; await renderer.RenderAsync(); MaskImage.Source = maskBitmap; maskBitmap.Invalidate(); Model.AnnotationsBitmap = (Bitmap)annotationsBitmap.AsBitmap(); } } else { MaskImage.Source = null; } } while (_processingPending && !_manipulating); Processing = false; } else { _processingPending = true; } }
private async Task<WriteableBitmap> ConvertPreviewToWriteableBitmap(SoftwareBitmap softwareBitmap, WriteableBitmap writeableBitmap) { int previewWidth = (int)m_renderer.PreviewSize.Width; int previewHeight = (int)m_renderer.PreviewSize.Height; if (writeableBitmap == null || writeableBitmap.PixelWidth != previewWidth || writeableBitmap.PixelHeight != previewHeight) { writeableBitmap = new WriteableBitmap(previewWidth, previewHeight); } if (softwareBitmap.PixelWidth != previewWidth || softwareBitmap.PixelHeight != previewHeight) { using (var renderer = new WriteableBitmapRenderer(new SoftwareBitmapImageSource(softwareBitmap))) { renderer.WriteableBitmap = writeableBitmap; await renderer.RenderAsync(); } } else { softwareBitmap.CopyToBuffer(writeableBitmap.PixelBuffer); } writeableBitmap.Invalidate(); return writeableBitmap; }
private async Task<WriteableBitmap> ConvertPreviewToWriteableBitmap(Bitmap bitmap, WriteableBitmap writeableBitmap) { int previewWidth = (int)m_renderer.PreviewSize.Width; int previewHeight = (int)m_renderer.PreviewSize.Height; if (writeableBitmap == null || writeableBitmap.PixelWidth != previewWidth || writeableBitmap.PixelHeight != previewHeight) { writeableBitmap = new WriteableBitmap(previewWidth, previewHeight); } if (bitmap.Dimensions != m_renderer.PreviewSize) { // Re-render Bitmap to WriteableBitmap at the correct size. using (var bitmapImageSource = new BitmapImageSource(bitmap)) using (var renderer = new WriteableBitmapRenderer(bitmapImageSource, writeableBitmap)) { renderer.RenderOptions = RenderOptions.Cpu; await renderer.RenderAsync().AsTask(); writeableBitmap.Invalidate(); } } else { // Already at the display size, so just copy. bitmap.CopyTo(writeableBitmap); writeableBitmap.Invalidate(); } return writeableBitmap; }
private static async void SourceCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { var url = e.NewValue as string; var image = d as Image; var imageBrush = d as ImageBrush; if (image != null) image.Source = null; else if (imageBrush != null) imageBrush.ImageSource = null; if (string.IsNullOrEmpty(url) || (image == null && imageBrush == null)) return; HttpResponseMessage resp = null; Stream stream; if (url.StartsWith("http")) { // Download the image using (var client = new HttpClient()) { resp = await client.GetAsync(url).ConfigureAwait(false); // If it fails, then abort! if (!resp.IsSuccessStatusCode) return; stream = await resp.Content.ReadAsStreamAsync().ConfigureAwait(false); } } else { // Get the file StorageFile file; if (url.StartsWith("ms-appx:")) { url = url.Replace("ms-appx://", ""); url = url.Replace("ms-appx:", ""); } if (url.StartsWith("ms-appdata:")) { url = url.Replace("ms-appdata:/local/", ""); url = url.Replace("ms-appdata:///local/", ""); file = await WinRtStorageHelper.GetFileAsync(url).ConfigureAwait(false); } else if (url.StartsWith("/")) file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx://" + url)) .AsTask() .ConfigureAwait(false); else file = await StorageFile.GetFileFromPathAsync(url).AsTask().ConfigureAwait(false); stream = await file.OpenStreamForReadAsync().ConfigureAwait(false); } using (stream) { if (stream.Length == 0) return; using (var rnd = stream.AsRandomAccessStream()) { // Then we can create the Random Access Stream Image using (var source = new RandomAccessStreamImageSource(rnd, ImageFormat.Undefined)) { // Create effect collection with the source stream using (var filters = new FilterEffect(source)) { double blurPercent = 1; await DispatcherHelper.RunAsync( () => blurPercent = GetBlurPercent(d)*256); // Initialize the filter and add the filter to the FilterEffect collection filters.Filters = new IFilter[] {new BlurFilter((int) blurPercent)}; // Create a target where the filtered image will be rendered to WriteableBitmap target = null; // Now that you have the raw bytes, create a Image Decoder var decoder = await BitmapDecoder.CreateAsync(rnd).AsTask().ConfigureAwait(false); // Get the first frame from the decoder because we are picking an image var frame = await decoder.GetFrameAsync(0).AsTask().ConfigureAwait(false); // Need to switch to UI thread for this await DispatcherHelper.RunAsync( () => { var wid = (int) frame.PixelWidth; var hgt = (int) frame.PixelHeight; target = new WriteableBitmap(wid, hgt); }).AsTask().ConfigureAwait(false); // Create a new renderer which outputs WriteableBitmaps using (var renderer = new WriteableBitmapRenderer(filters, target)) { rnd.Seek(0); // Render the image with the filter(s) await renderer.RenderAsync().AsTask().ConfigureAwait(false); // Set the output image to Image control as a source // Need to switch to UI thread for this await DispatcherHelper.RunAsync(() => { if (image != null) image.Source = target; else if (imageBrush != null) imageBrush.ImageSource = target; }).AsTask().ConfigureAwait(false); } } } } } if (resp != null) resp.Dispose(); }
/// <summary> /// Begins a photo stream item rendering process loop. Loop is executed asynchronously item by item /// until there are no more items in the queue. /// </summary> private async void Process() { _processingNow++; while (_enabled && Count > 0) { StreamItemViewModel item; if (_priorityQueue.Count > 0) { Busy = true; item = _priorityQueue[0]; _priorityQueue.RemoveAt(0); } else { item = _standardQueue[0]; _standardQueue.RemoveAt(0); } try { WriteableBitmap bitmap = null; Stream thumbnailStream = null; System.Diagnostics.Debug.Assert(item.RequestedSize != StreamItemViewModel.Size.None); if (item.RequestedSize == StreamItemViewModel.Size.Large) { bitmap = new WriteableBitmap(280, 280); thumbnailStream = item.Model.Picture.GetImage(); } else if (item.RequestedSize == StreamItemViewModel.Size.Medium) { bitmap = new WriteableBitmap(140, 140); thumbnailStream = item.Model.Picture.GetThumbnail(); } else { bitmap = new WriteableBitmap(70, 70); thumbnailStream = item.Model.Picture.GetThumbnail(); } thumbnailStream.Position = 0; using (StreamImageSource source = new StreamImageSource(thumbnailStream)) using (FilterEffect effect = new FilterEffect(source)) { List<IFilter> filters = new List<IFilter>(); if (item.RequestedSize == StreamItemViewModel.Size.Large) { int width = item.Model.Picture.Width; int height = item.Model.Picture.Height; if (width > height) { filters.Add(new CropFilter(new Windows.Foundation.Rect() { Width = height, Height = height, X = width / 2 - height / 2, Y = 0 })); } else { filters.Add(new CropFilter(new Windows.Foundation.Rect() { Width = width, Height = width, X = 0, Y = height / 2 - width / 2 })); } } if (item.Model.Filter != null) { foreach (IFilter f in item.Model.Filter.Components) { filters.Add(f); } } effect.Filters = filters; using (WriteableBitmapRenderer renderer = new WriteableBitmapRenderer(effect, bitmap)) { await renderer.RenderAsync(); } } item.TransitionToImage(bitmap); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Rendering stream item failed:" + ex.Message); item.TransitionToImage(null); } } _processingNow--; if (_processingNow == 0) { Busy = false; } }