public static async Task <WriteableBitmap> AdjustCurvesEffect(WriteableBitmap imgSource)
        {
            //var imgSource = new WriteableBitmap(bitmap.PixelWidth, bitmap.PixelHeight);
            //bitmap.CopyToBuffer(imgSource.PixelBuffer);

            var source = new BitmapImageSource(imgSource.AsBitmap());

            var curvesEffect = new CurvesEffect
            {
                Source = source
            };

            //allow for curve values to be set via settings pane with
            var globalCurve = new Curve(CurveInterpolation.NaturalCubicSpline, new[]
            {
                new Point(200, 62)
            });

            //156, 78
            //new Point(110, 34)

            curvesEffect.Red   = globalCurve;
            curvesEffect.Green = globalCurve;
            curvesEffect.Blue  = globalCurve;

            var adjustedImg = new WriteableBitmap(imgSource.PixelWidth, imgSource.PixelHeight);

            using (var renderer = new WriteableBitmapRenderer(curvesEffect, adjustedImg))
            {
                // Generate the gray image
                await renderer.RenderAsync();
            }

            return(adjustedImg);
        }
Esempio n. 2
0
        public int crearCodQr()
        {
            if (!validaCampos("codigoQr"))
            {
                return(0);
            }

            /*
             * String rechazado = "";
             * rechazado = lblRechazo.Content.ToString();
             * if(rechazado != "")
             * {
             *  rechazado = "x";
             * }
             */
            String  tipos = "";
            dynamic asd   = cbxTipos;

            if (cbxTipos.SelectedValue.ToString() == "1")
            {
                tipos = "x";
            }
            else
            {
                tipos = cbxTipos.SelectedValue.ToString();
            }
            int    correlativo = Convert.ToInt16(cantEtiquetas.Value.ToString());
            String codigoQr    = "";

            codigoQr = "{" +
                       "\"lt\":\"" + txtLote.Text + "\"," +
                       "\"mt\":\"" + cbxMaterial.SelectedValue + "\"," +
                       "\"pr\":\"" + txtPorcion.Text + "\"," +
                       "\"cr\":\"" + txtCorrelativo.Text + "\"," +
                       "\"f\":\"" + fechaPicker.SelectedDate.Value.ToString("dd-MM-yyyy") + "\"," +
                       "\"ev\":\"" + cbxEnvase.SelectedValue + "\"," +
                       //"\"almacen\":\"" + cbxAlmacen.Text + "\"," +
                       "\"jl\":\"" + lblJuliano.Content.ToString() + "\"," +
                       "\"an\":\"" + lblAño.Content.ToString() + "\"," +
                       "\"or\":\"" + cbxOrigenes.SelectedValue.ToString() + "\"," +
                       "\"rz\":\"" + tipos + "\"," +
                       "\"ct\":\"" + cantToneladas.Value.ToString() + "\"" +
                       "}";
            //or
            //testeo.Content = tipos;


            QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode    qrCode;

            encoder.TryEncode(codigoQr, out qrCode);
            WriteableBitmapRenderer wRenderer = new WriteableBitmapRenderer(new FixedModuleSize(2, QuietZoneModules.Two), Colors.Black, Colors.White);
            WriteableBitmap         wBitmap   = new WriteableBitmap(104, 104, 170, 170, PixelFormats.Gray8, null);

            wRenderer.Draw(wBitmap, qrCode.Matrix);

            imgQrCode.Source = wBitmap;

            return(0);
        }
Esempio n. 3
0
        public async Task <WriteableBitmap> LayHinhThuNho(int side)
        {
            int  minSide = Width < Height ? Width : Height;
            Rect rect    = new Rect()
            {
                X      = (Width - minSide) / 2,
                Y      = (Height - minSide) / 2,
                Height = minSide,
                Width  = minSide
            };

            _filters.Add(new CropFilter(rect));
            WriteableBitmap bitmap = new WriteableBitmap(side, side);

            using (FilterEffect effect = new FilterEffect(ImageSource))
            {
                effect.Filters = _filters;
                using (WriteableBitmapRenderer render = new WriteableBitmapRenderer(effect, bitmap))
                {
                    await render.RenderAsync();

                    bitmap.Invalidate();
                }
            }

            _filters.RemoveAt(_filters.Count - 1);
            return(bitmap);
        }
        /// <summary>
        /// Initialize and start the camera preview
        /// </summary>
        public async Task InitializeAsync()
        {
            Status = "Starting camera...";

            // Create a camera preview image source (from Imaging SDK)
            _cameraPreviewImageSource = new CameraPreviewImageSource();
            await _cameraPreviewImageSource.InitializeAsync(string.Empty);

            var properties = await _cameraPreviewImageSource.StartPreviewAsync();

            // Create a preview bitmap with the correct aspect ratio
            var width  = 640.0;
            var height = (width / properties.Width) * properties.Height;
            var bitmap = new WriteableBitmap((int)width, (int)height);

            PreviewBitmap = bitmap;

            // Create a filter effect to be used with the source (no filters yet)
            _effect = new FilterEffect(_cameraPreviewImageSource);
            _writeableBitmapRenderer = new WriteableBitmapRenderer(_effect, _writeableBitmap);

            // Attach preview frame delegate
            _cameraPreviewImageSource.PreviewFrameAvailable += OnPreviewFrameAvailable;

            Status = _filterList[_index].Name;

            Initialized = true;
            NextFilterCommand.RaiseCanExecuteChanged();
            PreviousFilterCommand.RaiseCanExecuteChanged();
        }
Esempio n. 5
0
        public async Task ApplyRotationFilterAsync(double value)
        {
            RotationFilterModel f = new RotationFilterModel(value);

            IsChanged = true;
            FilterList.Add(f);
            foreach (var item in f.Components)
            {
                _filters.Add(item);
            }

            int h = Math.Max(OriginalBitmap.PixelHeight, OriginalBitmap.PixelWidth);
            int w = Math.Min(OriginalBitmap.PixelHeight, OriginalBitmap.PixelWidth);

            OriginalBitmap = new WriteableBitmap(w, h);

            using (FilterEffect effect = new FilterEffect(ImageSource)
            {
                Filters = _filters
            })
                using (WriteableBitmapRenderer renderer = new WriteableBitmapRenderer(effect, OriginalBitmap))
                {
                    await renderer.RenderAsync();

                    OriginalBitmap.Invalidate();
                }
        }
        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);
        }
Esempio n. 8
0
        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;
            }
            
        }
Esempio n. 9
0
        /// <summary>
        /// Initialize and start the camera preview
        /// </summary>
        public async Task InitializeAsync()
        {
            Status = "Starting camera...";

            // Create a camera preview image source (from Imaging SDK)
            _cameraPreviewImageSource = new CameraPreviewImageSource();

            DeviceInformationCollection devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(Windows.Devices.Enumeration.DeviceClass.VideoCapture);

            String backCameraId = devices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back).Id;

            await _cameraPreviewImageSource.InitializeAsync(backCameraId);

            var properties = await _cameraPreviewImageSource.StartPreviewAsync();

            // Create a preview bitmap with the correct aspect ratio
            var width  = 640.0;
            var height = (width / properties.Width) * properties.Height;
            var bitmap = new WriteableBitmap((int)width, (int)height);

            PreviewBitmap = bitmap;

            // Create a filter effect to be used with the source (no filters yet)

            _writeableBitmapRenderer = new WriteableBitmapRenderer(_cameraPreviewImageSource, _writeableBitmap);

            // Attach preview frame delegate
            _cameraPreviewImageSource.PreviewFrameAvailable += OnPreviewFrameAvailable;

            Status = "Initialized";

            Initialized = true;
        }
Esempio n. 10
0
        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();
            }
        }
Esempio n. 11
0
        private void Cleanup()
        {
            System.Diagnostics.Debug.WriteLine("Cleaning up scanner");
            try
            {
                _Ready     = false;
                _Done      = true;
                _Rendering = true;

                _Controller   = null;
                _ImagePreview = null;
                _Effects      = null;

                _Render.Dispose();
                _Render = null;
                _Image  = null;

                _Source.StopPreviewAsync();
                _Source.PreviewFrameAvailable -= OnPreviewFrameAvailable;
                _Source.Dispose();
                _Source = null;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Cleaning up scanner. {0}", ex.Message);
            }
        }
Esempio n. 12
0
        private static WriteableBitmap RenderQrcodeImage(string data)
        {
            try
            {
                QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.M);
                QrCode    qrCode;
                encoder.TryEncode(data, out qrCode);
                WriteableBitmapRenderer wRenderer = new WriteableBitmapRenderer(new FixedModuleSize(2, QuietZoneModules.Two), Colors.Black, Colors.White);
                WriteableBitmap         wBitmap   = new WriteableBitmap(70, 70, 96, 96, PixelFormats.Gray8, null);
                wRenderer.Draw(wBitmap, qrCode.Matrix);

                return(wBitmap);
            }
            catch (Exception)
            {
                QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.M);
                QrCode    qrCode;
                encoder.TryEncode("test", out qrCode);
                WriteableBitmapRenderer wRenderer = new WriteableBitmapRenderer(new FixedModuleSize(2, QuietZoneModules.Two), Colors.Black, Colors.White);
                WriteableBitmap         wBitmap   = new WriteableBitmap(70, 70, 96, 96, PixelFormats.Gray8, null);
                wRenderer.Draw(wBitmap, qrCode.Matrix);

                return(wBitmap);
            }
        }
Esempio n. 13
0
        private void Uninitialize()
        {
            _initialized = false;

            if (_timer != null)
            {
                _timer.Stop();
                _timer.Tick -= DispatcherTimer_Tick;
                _timer       = null;
            }

            if (_renderer != null)
            {
                _renderer.Dispose();
                _renderer = null;
            }

            if (_effect != null)
            {
                _effect.Dispose();
                _effect = null;
            }

            _filters         = null;
            _chromaKeyFilter = null;
            _rotationFilter  = null;
            _bitmap          = null;

            if (_source != null)
            {
                _source.Dispose();
                _source = null;
            }
        }
Esempio n. 14
0
        /// <summary>
        /// GetImage by Filter
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public async static Task <WriteableBitmap> GetImageByFilter(this IRandomAccessStream stream, IFilter filter)
        {
            stream.Seek(0);
            var imageFormat = ImageFormat.Jpeg;
            var imageType   = await getImageType(stream);

            if (imageType == ImageType.PNG)
            {
                imageFormat = ImageFormat.Png;
            }
            using (var source = new RandomAccessStreamImageSource(stream, imageFormat))
            {
                // Create effect collection with the source stream
                using (var filters = new FilterEffect(source))
                {
                    // Initialize the filter and add the filter to the FilterEffect collection
                    filters.Filters = new IFilter[] { filter };

                    // Create a target where the filtered image will be rendered to
                    var target = new WriteableBitmap((int)(Window.Current.Bounds.Width), (int)(Window.Current.Bounds.Height));

                    // Create a new renderer which outputs WriteableBitmaps
                    using (var renderer = new WriteableBitmapRenderer(filters, target))
                    {
                        // Render the image with the filter(s)
                        target = await renderer.RenderAsync();

                        target.Invalidate();
                        return(target);
                    }
                }
            }
        }
Esempio n. 15
0
        private async void ViewfinderCanvas_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var point  = e.GetPosition(ViewfinderCanvas);
            var bitmap = new WriteableBitmap((int)ViewfinderCanvas.ActualWidth, (int)ViewfinderCanvas.ActualHeight);

            using (var source = new CameraPreviewImageSource(App.Camera))
                using (var effect = new FilterEffect(source))
                    using (var renderer = new WriteableBitmapRenderer(effect, bitmap, OutputOption.Stretch))
                    {
                        effect.Filters = new List <IFilter>()
                        {
                            new RotationFilter(_rotationFilter.RotationAngle)
                        };

                        await renderer.RenderAsync();

                        var picked = bitmap.Pixels[((int)point.Y) * bitmap.PixelWidth + ((int)point.X)];

                        _color = new Color
                        {
                            A = 0xFF,
                            R = (byte)((picked & 0x00FF0000) >> 16),
                            G = (byte)((picked & 0x0000FF00) >> 8),
                            B = (byte)(picked & 0x000000FF)
                        };
                    }

            ColorBorder.Background = new SolidColorBrush(_color);
        }
        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
            {
               
            }


        }
        /// <summary>
        /// uses the BarcodeWriterGeneric implementation and the <see cref="WriteableBitmapRenderer"/> class for decoding
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static WriteableBitmap WriteAsWriteableBitmap(this IBarcodeWriterGeneric writer, string content)
        {
            var bitmatrix = writer.Encode(content);
            var renderer  = new WriteableBitmapRenderer();

            return(renderer.Render(bitmatrix, writer.Format, content, writer.Options));
        }
Esempio n. 18
0
        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;
            }
        }
Esempio n. 19
0
        public async Task <StorageFile> ApplyFilter(StorageFile file, FilterOption filterOption)
        {
            IImageProvider source = null;

            var properties = await file.Properties.GetImagePropertiesAsync();

            this.SelectFilter(filterOption);

            using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                source = new StreamImageSource(stream.AsStream(), ImageFormat.Jpeg);

                using (var filterEffect = new FilterEffect(source))
                {
                    // Initialize the filter and add the filter to the FilterEffect collection
                    //var filter = new SketchFilter(SketchMode.Gray);

                    filterEffect.Filters = new IFilter[] { this.SelectedFilter };

                    // Create a target where the filtered image will be rendered to
                    var target = new WriteableBitmap((int)properties.Width, (int)properties.Height);

                    // Create a new renderer which outputs WriteableBitmaps
                    using (var renderer = new WriteableBitmapRenderer(filterEffect, target))
                    {
                        // Render the image with the filter(s)
                        await renderer.RenderAsync();

                        return(await this.WriteableBitmapToStorageFile(target, FileFormat.Jpeg));
                    }
                }
            }
        }
Esempio n. 20
0
        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;
            }
        }
 public CustomEffectViewModel(IImageProvider effect)
 {
     Effect            = effect;
     m_writeableBitmap = new WriteableBitmap(100, 100);
     m_renderer        = new WriteableBitmapRenderer(Effect, m_writeableBitmap);
     MinValue          = 0;
     MaxValue          = 1;
 }
 public CustomEffectViewModel(IImageProvider effect)
 {
     Effect = effect;            
     m_writeableBitmap = new WriteableBitmap(100, 100);
     m_renderer = new WriteableBitmapRenderer(Effect, m_writeableBitmap);
     MinValue = 0;
     MaxValue = 1;
 }
Esempio n. 23
0
        /// <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;
                }
            }
        }
Esempio n. 24
0
        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;
                }
            }
        }
 public CustomEffectViewModel(IImageProvider effect, string propertyName, double minValue, double maxValue)
 {
     m_propertyName = propertyName;
     Effect = effect;
     m_writeableBitmap = new WriteableBitmap(100, 100);
     m_renderer = new WriteableBitmapRenderer(Effect, m_writeableBitmap);
     MinValue = minValue;
     MaxValue = maxValue;
 }
 public CustomEffectViewModel(IImageProvider effect, string propertyName, double minValue, double maxValue)
 {
     m_propertyName    = propertyName;
     Effect            = effect;
     m_writeableBitmap = new WriteableBitmap(100, 100);
     m_renderer        = new WriteableBitmapRenderer(Effect, m_writeableBitmap);
     MinValue          = minValue;
     MaxValue          = maxValue;
 }
Esempio n. 27
0
 /// <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());
             }
 }
Esempio n. 28
0
        private async Task InitCamera()
        {
            var devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(Windows.Devices.Enumeration.DeviceClass.VideoCapture);

            string deviceId = devices.FirstOrDefault(d => d.EnclosureLocation.Panel != Windows.Devices.Enumeration.Panel.Front).Id;

            _Source = new CameraPreviewImageSource();
            await _Source.InitializeAsync(deviceId);

            _Source.PreviewFrameAvailable += OnPreviewFrameAvailable;

            //  set auto focus
            _Controller = (VideoDeviceController)_Source.VideoDeviceController;
            if (_Controller.FocusControl.Supported)
            {
                try
                {
                    if (_Controller.FocusControl.WaitForFocusSupported)
                    {
                        _Controller.FocusControl.Configure(new FocusSettings {
                            Mode = FocusMode.Continuous
                        });
                    }
                    else
                    {
                        _Controller.FocusControl.Configure(new FocusSettings {
                            Mode = FocusMode.Auto
                        });
                    }
                }
                catch
                {
                    _Controller.FocusControl.Configure(new FocusSettings {
                        Mode = FocusMode.Auto
                    });
                }
            }

            if (_Controller.FlashControl.Supported)
            {
                _Controller.FlashControl.Auto = true;
            }
            if (_Controller.ExposureControl.Supported)
            {
                _Controller.ExposureControl.SetAutoAsync(true);
            }

            _Image = new WriteableBitmap((int)Window.Current.Bounds.Width, (int)Window.Current.Bounds.Height);
            //  filters
            _Effects         = new FilterEffect(_Source);
            _Effects.Filters = new IFilter[] { new GrayscaleFilter() };

            _Render = new WriteableBitmapRenderer(_Effects, _Image);
            _Ready  = true;
        }
Esempio n. 29
0
        /// <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();
                    }

                    TmpBitmap.Pixels.CopyTo(PreviewBitmap.Pixels, 0);
                    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;
                }
            }
        }
Esempio n. 30
0
        public WriteableBitmap generateQRCode(Ticket t)
        {
            QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.H);
            var       res     = encoder.Encode(t.TicketID + "");

            WriteableBitmapRenderer wRenderer = new WriteableBitmapRenderer(new FixedModuleSize(2, QuietZoneModules.Two), Colors.Black, Colors.White);
            WriteableBitmap         wBitmap   = new WriteableBitmap(51, 51, 5, 5, PixelFormats.Gray8, null);

            wRenderer.Draw(wBitmap, res.Matrix);
            return(wBitmap);
        }
Esempio n. 31
0
        private async void Init()
        {
            //Get back camera
            var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            var backCameraId =
                devices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == Panel.Back).Id;

            //Start preview
            _cameraPreviewImageSource = new CameraPreviewImageSource();
            await _cameraPreviewImageSource.InitializeAsync(backCameraId);

            var properties = await _cameraPreviewImageSource.StartPreviewAsync();

            //Setup preview
            _width  = 640.0;
            _height = _width / properties.Width * properties.Height;
            var bitmap = new WriteableBitmap((int)_width, (int)_height);

            _writeableBitmap = bitmap;

            PreviewImage.Source = _writeableBitmap;

            _writeableBitmapRenderer = new WriteableBitmapRenderer(_cameraPreviewImageSource, _writeableBitmap);

            _cameraPreviewImageSource.PreviewFrameAvailable += OnPreviewFrameAvailable;

            _videoDevice = (VideoDeviceController)_cameraPreviewImageSource.VideoDeviceController;

            //Set timer for auto focus
            if (_videoDevice.FocusControl.Supported)
            {
                var focusSettings = new FocusSettings
                {
                    AutoFocusRange        = AutoFocusRange.Macro,
                    Mode                  = FocusMode.Auto,
                    WaitForFocus          = false,
                    DisableDriverFallback = false
                };

                _videoDevice.FocusControl.Configure(focusSettings);

                _timer = new DispatcherTimer
                {
                    Interval = new TimeSpan(0, 0, 0, 2, 0)
                };
                _timer.Tick += TimerOnTick;
                _timer.Start();
            }

            await _videoDevice.ExposureControl.SetAutoAsync(true);

            _initialized = true;
        }
Esempio n. 32
0
        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;
                }
            }
        }
Esempio n. 35
0
        /// <summary>
        /// Initialize and start the camera preview
        /// </summary>
        public async Task InitializeAsync()
        {
            if (CaptureButton.Content.ToString().Equals("Capture and Canny"))
            {
                CaptureButton.Content = "Stop";

                // Create a camera preview image source (from Imaging SDK)
                if (_cameraPreviewImageSource == null)
                {
                    _cameraPreviewImageSource = new CameraPreviewImageSource();
                    await _cameraPreviewImageSource.InitializeAsync(string.Empty);
                }

                var properties = await _cameraPreviewImageSource.StartPreviewAsync();

                // Create a preview bitmap with the correct aspect ratio
                var width  = 640.0;
                var height = (width / properties.Width) * properties.Height;
                var bitmap = new WriteableBitmap((int)width, (int)height);

                _writeableBitmap = bitmap;

                // Create a filter effect to be used with the source (e.g. used to correct rotation)
                //_effect = new FilterEffect(_cameraPreviewImageSource);
                //_effect.Filters = new IFilter[] { new RotationFilter(90.0) };
                //_writeableBitmapRenderer = new WriteableBitmapRenderer(_effect, _writeableBitmap);

                RotationEffect rotation = new RotationEffect(_cameraPreviewImageSource, 90);

                _writeableBitmapRenderer = new WriteableBitmapRenderer(rotation, _writeableBitmap);
                //_writeableBitmapRenderer.Source = new EffectList() { _cameraPreviewImageSource, rotation };
                //_writeableBitmapRenderer.WriteableBitmap = _writeableBitmap;

                ImageView.Source = _writeableBitmap;

                // Attach preview frame delegate

                _cameraPreviewImageSource.PreviewFrameAvailable += OnPreviewFrameAvailable;
            }
            else
            {
                if (CaptureButton.Content.ToString().Equals("Stop"))
                {
                    await _cameraPreviewImageSource.StopPreviewAsync();

                    _cameraPreviewImageSource.Dispose();
                    _cameraPreviewImageSource = null;
                }
                CaptureButton.Content = "Capture and Canny";
                ImageView.Source      = null;
            }
        }
Esempio n. 36
0
        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();

        }
Esempio n. 37
0
        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();
        }
        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;
                }
            }
        }
        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;
            }
        }
Esempio n. 41
0
        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;
        }
Esempio n. 42
0
      /// <summary>
      /// Initialize and start the camera preview
      /// </summary>
      public async Task InitializeAsync()
      {
         if (CaptureButton.Content.ToString().Equals("Capture and Canny"))
         {
            CaptureButton.Content = "Stop";

            // Create a camera preview image source (from Imaging SDK)
            if (_cameraPreviewImageSource == null)
            {
               _cameraPreviewImageSource = new CameraPreviewImageSource();
               await _cameraPreviewImageSource.InitializeAsync(string.Empty);
            }

            var properties = await _cameraPreviewImageSource.StartPreviewAsync();

            // Create a preview bitmap with the correct aspect ratio
            var width = 640.0;
            var height = (width / properties.Width) * properties.Height;
            var bitmap = new WriteableBitmap((int)width, (int)height);

            _writeableBitmap = bitmap;

            // Create a filter effect to be used with the source (e.g. used to correct rotation)
            _effect = new FilterEffect(_cameraPreviewImageSource);
            _effect.Filters = new IFilter[] { new RotationFilter(90.0) };
            _writeableBitmapRenderer = new WriteableBitmapRenderer(_effect, _writeableBitmap);

            ImageView.Source = _writeableBitmap;

            // Attach preview frame delegate
            _cameraPreviewImageSource.PreviewFrameAvailable += OnPreviewFrameAvailable;
         }
         else
         {
            if (CaptureButton.Content.ToString().Equals("Stop"))
            {
               await _cameraPreviewImageSource.StopPreviewAsync();
               _cameraPreviewImageSource.Dispose();
               _cameraPreviewImageSource = null;
            }
            CaptureButton.Content = "Capture and Canny";
            ImageView.Source = null;
         }
      }
        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;
            }


        }
        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
            {
                // 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 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 bool isRendering; // Used to prevent multiple renderers running at once

        public async Task InitializeAsync()
        {
            // Discover all the cameras
            await EnumerateCamerasAsync();
            
            // Create a camera preview image source (from Imaging SDK)
            cameraPreviewImageSource = new CameraPreviewImageSource();
            await cameraPreviewImageSource.InitializeAsync(backCamera.Id);
            var properties = await cameraPreviewImageSource.StartPreviewAsync();

            VideoDeviceController controller = (VideoDeviceController)cameraPreviewImageSource.VideoDeviceController;            

            // Create a preview bitmap with the correct aspect ratio
            var width = properties.Width;
            var height = properties.Height;
            var bitmap = new WriteableBitmap((int)width, (int)height);

            outputBitmap = bitmap;

            // Create a filter effect to be used with the source (no filters yet)
            //effect = new LensBlurEffect(cameraPreviewImageSource, new LensBlurPredefinedKernel(LensBlurPredefinedKernelShape.Circle, 50));
            effect = new FilterEffect(cameraPreviewImageSource);

            var blur = new BlurFilter();
            blur.KernelSize = 30;
            blur.BlurRegionShape = BlurRegionShape.Elliptical;
            effect.Filters = new[] { blur };

            renderer = new WriteableBitmapRenderer(effect, outputBitmap);

            Initialized = true;

            CaptureImage.Source = outputBitmap;

            // Attach preview frame delegate
            cameraPreviewImageSource.PreviewFrameAvailable += OnPreviewFrameAvailable;
        }
        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;
        }
Esempio n. 49
0
        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();
            }

        }
Esempio n. 52
0
        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();
        }
        public void Dispose()
        {
            if (source != null)
            {
                source.Dispose(); source = null;
                filter.Dispose(); filter = null;
                reframing = null;
                rendererLR.Dispose(); rendererLR = null;
                rendererHR.Dispose(); rendererHR = null;
            }
            outputBitmapLRTmp = null;
            outputBitmapLR = null;
            outputBitmapHRTmp = null;
            outputBitmapHR = null;

            if (output != null)
            {
                output.ManipulationStarted -= ManipulationStarted;
                output.ManipulationDelta -= ManipulationDelta;
                output.ManipulationCompleted -= ManipulationCompleted;
            }
            output = null;
        }
        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;
            }


        }
        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();
            }


        }
Esempio n. 57
0
        /// <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;
                }
            }
        }
        async void setInput(Stream s)
        {

            //Dispose old session ressources.
            if (source != null)
            {
                source.Dispose(); source = null;
                filter.Dispose(); filter = null;
                reframing = null;
                rendererLR.Dispose(); rendererLR = null;
                rendererHR.Dispose(); rendererHR = null;
            }
            //reset stream position
            s.Seek(0, SeekOrigin.Begin);

            MemoryStream mstream = new MemoryStream();
            s.CopyTo(mstream);
            var tmpsource = new BufferImageSource(mstream.GetBuffer().AsBuffer());
           // var tmpsource = new StreamImageSource(s);
            {

                var info = await tmpsource.GetInfoAsync();

                filter = new FilterEffect(tmpsource);

                reframing = new ReframingFilter();
                filter.Filters = new IFilter[] { reframing };
                rendererLR = new WriteableBitmapRenderer(filter, outputBitmapLRTmp);
                rendererHR = new WriteableBitmapRenderer(filter, outputBitmapHRTmp);

                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 = output.Height / info.ImageSize.Height;
                }
                else
                {
                    currentScale = output.Width / info.ImageSize.Width;
                }
                currentAngle = 0.0;
                saveLastPossaveLastPositionData();
                GC.Collect();
            }
            source = tmpsource;
            requestProcessing();
        }
Esempio n. 59
0
        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>
        /// 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;
            }
        }