Inheritance: BitmapSource, IWriteableBitmap
コード例 #1
1
        private async void ButtonFilePick_Click(object sender, RoutedEventArgs e)
        {
            var picker = new FileOpenPicker();
            picker.ViewMode = PickerViewMode.Thumbnail;
            picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            picker.FileTypeFilter.Add(".jpg");
            picker.FileTypeFilter.Add(".jpeg");
            picker.FileTypeFilter.Add(".png");

            StorageFile file = await picker.PickSingleFileAsync();


            if (file != null)
            {

                ImageProperties imgProp = await file.Properties.GetImagePropertiesAsync();
                var savedPictureStream = await file.OpenAsync(FileAccessMode.Read);

                //set image properties and show the taken photo
                bitmap = new WriteableBitmap((int)imgProp.Width, (int)imgProp.Height);
                await bitmap.SetSourceAsync(savedPictureStream);
                BBQImage.Source = bitmap;
                BBQImage.Visibility = Visibility.Visible;

                (this.DataContext as BBQRecipeViewModel).imageSource = file.Path;
            }
        }
コード例 #2
0
 private static async Task<WriteableBitmap> read()
 {
     using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
     {
         BitmapDecoder decoder = await BitmapDecoder.CreateAsync(BitmapDecoder.JpegDecoderId, stream);
         uint width = decoder.PixelWidth;
         uint height = decoder.PixelHeight;
         if (angle % 180 != 0)
         {
             width = decoder.PixelHeight;
             height = decoder.PixelWidth;
         }
         Dictionary<int, BitmapRotation> angles = new Dictionary<int, BitmapRotation>()
         {
             { 0, BitmapRotation.None },
             { 90,  BitmapRotation.Clockwise90Degrees },
             { 180,  BitmapRotation.Clockwise180Degrees },
             { 270, BitmapRotation.Clockwise270Degrees },
             { 360, BitmapRotation.None }
         };
         BitmapTransform transform = new BitmapTransform();
         transform.Rotation = angles[angle];
         PixelDataProvider data = await decoder.GetPixelDataAsync(
         BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, transform,
         ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage);
         bitmap = new WriteableBitmap((int)width, (int)height);
         byte[] buffer = data.DetachPixelData();
         using (Stream pixels = bitmap.PixelBuffer.AsStream())
         {
             pixels.Write(buffer, 0, (int)pixels.Length);
         }
     }
     return bitmap;
 }
コード例 #3
0
ファイル: QRCode.xaml.cs プロジェクト: ddumic/WP_8_1_helper
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            await InitializeQrCode();
            var imgProp = new ImageEncodingProperties { Subtype = "BMP", Width = 600, Height = 800 };
            var bcReader = new BarcodeReader();

            while (true)
            {
                var stream = new InMemoryRandomAccessStream();
                await _mediaCapture.CapturePhotoToStreamAsync(imgProp, stream);

                stream.Seek(0);
                var wbm = new WriteableBitmap(600, 800);
                await wbm.SetSourceAsync(stream);

                var result = bcReader.Decode(wbm);

                if (result != null)
                {
                    var msgbox = new MessageDialog(result.Text);
                    await msgbox.ShowAsync();
                }
            }

        }
コード例 #4
0
ファイル: Device.cs プロジェクト: shecodez/Axion
 public Device(WriteableBitmap bmp)
 {
     this.bmp = bmp;
     // The back buffer size is equal to the number of pixels to draw
     // on screen (width*height) * 4 (R,G,B & Alpha values).
     backBuffer = new byte[bmp.PixelWidth * bmp.PixelHeight * 4];
 }
コード例 #5
0
ファイル: Lpd8806Matrix.cs プロジェクト: ms-iot/LEDMatrix
        /// <summary>
        /// Displays an image on the LED matrix
        /// </summary>
        /// <param name="image">Bitmap to display on the LED matrix</param>
        /// <returns>Task for tracking the status of the async call</returns>
        public async Task DisplayImage(WriteableBitmap image)
        {
            WriteableBitmap resizedBitmap = image.Resize(
                this.PixelWidth,
                this.PixelHeight,
                WriteableBitmapExtensions.Interpolation.Bilinear);

            List<Color> colors = resizedBitmap.Flip(WriteableBitmapExtensions.FlipMode.Horizontal).ToColorList();

            colors = colors.FlipEvenColumns(this.PixelHeight);

            List<Color> perceptualColors = colors.Select(
                color => color.ToPerceptual().ApplyGamma(1.5)).ToList();

            colors.Clear();
            colors.AddRange(perceptualColors);

            colors.RemoveAt(MagicPixel);

            IEnumerable<byte> bytes = colors.Get21BitPixelBytes();

            App.Firmata.sendSysex(LED_RESET, new Buffer(0));
            await Task.Delay(1);

            App.Firmata.SendPixelBlob(bytes, 30);
            await Task.Delay(1);

            App.Firmata.sendSysex(LED_RESET, new Buffer(0));
            await Task.Delay(1);
        }
コード例 #6
0
        private async Task SaveStrokesToBitmap(WriteableBitmap b)
        {
            Rect imgRect = new Rect(0, 0, b.PixelWidth, b.PixelHeight);
            InkStrokeContainer container = TheInkCanvas.InkPresenter.StrokeContainer;
            InkStrokeBuilder builder = new InkStrokeBuilder();

            // Unsichtbare Tinte!
            InkDrawingAttributes da = TheInkCanvas.InkPresenter.CopyDefaultDrawingAttributes();
            da.Size = new Size(0.1, 0.1);
            builder.SetDefaultDrawingAttributes(da);

            // Strich in oberer linker Ecke einfügen
            InkStroke topLeft = builder.CreateStroke(new List<Point>() {
                new Point(1, 1),
                new Point(2, 2) });
            container.AddStroke(topLeft);

            // Strich in unterer Rechter Ecke einfügen
            InkStroke bottomRight = builder.CreateStroke(new List<Point>() {
                new Point(imgRect.Width -2, imgRect.Height -2),
                new Point(imgRect.Width -1, imgRect.Height -1) });   
            container.AddStroke(bottomRight);

            // Striche in WriteableBitmap speichern
            WriteableBitmap bmp;
            using (InMemoryRandomAccessStream ims =
                new InMemoryRandomAccessStream())
            {
                await container.SaveAsync(ims);
                bmp = await new WriteableBitmap(1, 1)
                    .FromStream(ims, BitmapPixelFormat.Bgra8);
            }
            // Bilder zusammenfügen
            b.Blit(imgRect, bmp, imgRect, WriteableBitmapExtensions.BlendMode.Alpha);
        }
コード例 #7
0
        private static async Task<FileUpdateStatus> WriteToStorageFile(WriteableBitmap bitmap, StorageFile file)
        {
            StorageFile sFile = file;
            if (sFile != null)
            {
                CachedFileManager.DeferUpdates(sFile);

                using (var fileStream = await sFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);
                    Stream pixelStream = bitmap.PixelBuffer.AsStream();
                    byte[] pixels = new byte[pixelStream.Length];
                    await pixelStream.ReadAsync(pixels, 0, pixels.Length);
                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                        (uint) bitmap.PixelWidth,
                        (uint) bitmap.PixelHeight,
                        96.0,
                        96.0,
                        pixels);
                    await encoder.FlushAsync();
                }

                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(sFile);
                return status;
            }
            return FileUpdateStatus.Failed;
        }
コード例 #8
0
ファイル: BlurImageView.xaml.cs プロジェクト: powerytg/prism
        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;
            }
            
        }
コード例 #9
0
ファイル: MainPage.xaml.cs プロジェクト: rthome/softrender
        private async void PageLoaded(object sender, RoutedEventArgs e)
        {
            var bmp = new WriteableBitmap(1024, 768);
            imageControl.Source = bmp;

            device = new RenderDevice(bmp);
            camera = new Camera
            {
                Position = new Vector3(0, 0, 10.0f),
                Target = Vector3.Zero
            };

            var importer = new BabylonImporter();
            var importedMeshes = await importer.LoadFileAsync("model.babylon");

            meshes = new List<Mesh>();
            foreach(var mesh in importedMeshes)
                meshes.Add(mesh);
            foreach(var mesh in importedMeshes)
            {
                var newMesh = new Mesh("MonkeyClone", mesh.Vertices, mesh.Faces);
                newMesh.Position = new Vector3(2.65f, 0, 0);
                meshes.Add(newMesh);
            }

            CompositionTarget.Rendering += Render;
        }
コード例 #10
0
 public static WriteableBitmap Overlay(WriteableBitmap bmp, WriteableBitmap overlay, Point location)
 {
     var result = bmp.Clone();
     var size = new Size(overlay.PixelWidth, overlay.PixelHeight);
     result.Blit(new Rect(location, size), overlay, new Rect(new Point(0, 0), size), WriteableBitmapExtensions.BlendMode.Alpha);
     return result;
 }
コード例 #11
0
ファイル: MainPage.xaml.cs プロジェクト: shecodez/Axion
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            // Choose the back buffer resolution here.
            WriteableBitmap bmp = new WriteableBitmap(640, 480);

            device = new Device(bmp);

            // Image XAML control
            frontBuffer.Source = bmp;

            mesh.Vertices[0] = new Vector3(-1, 1, 1);
            mesh.Vertices[1] = new Vector3(1, 1, 1);
            mesh.Vertices[2] = new Vector3(-1, -1, 1);
            mesh.Vertices[3] = new Vector3(-1, -1, -1);
            mesh.Vertices[4] = new Vector3(-1, 1, -1);
            mesh.Vertices[5] = new Vector3(1, 1, -1);
            mesh.Vertices[6] = new Vector3(1, -1, 1);
            mesh.Vertices[7] = new Vector3(1, -1, -1);

            camera.Position = new Vector3(0, 0, 10.0f);
            camera.Target = Vector3.Zero;

            // Registering to the XAML rendering Loop
            CompositionTarget.Rendering += CompositionTarget_Rendering;
        }
コード例 #12
0
ファイル: MainPage.xaml.cs プロジェクト: forehalo/UWP-dev
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            StorageFile imgFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/1.jpg"));
            using (IRandomAccessStream streamIn = await imgFile.OpenReadAsync())
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(BitmapDecoder.JpegDecoderId, streamIn);
                // 获取像素数据
                PixelDataProvider provd = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, new BitmapTransform(), ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage);
                byte[] srcData = provd.DetachPixelData();
                // 灰度处理
                for (int i = 0; i < srcData.Length; i += 4)
                {
                    double b = srcData[i];
                    double g = srcData[i + 1];
                    double r = srcData[i + 2];

                    double v = (b + g + r) / 3d;

                    srcData[i] = srcData[i + 1] = srcData[i + 2] = Convert.ToByte(v);
                }

                WriteableBitmap wbitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                srcData.CopyTo(wbitmap.PixelBuffer);
                this.imgGray.Source = wbitmap;
            }
        }
コード例 #13
0
        public static async Task<WriteableBitmap> StorageFileToWriteableBitmapWithDirection(StorageFile file)
        {
            if (file == null)
                return null;
            using (IRandomAccessStream stream = await file.OpenReadAsync())
            {

                // Create a decoder from the stream. With the decoder, we can get 
                // the properties of the image.
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                PixelDataProvider pix = await decoder.GetPixelDataAsync(
                BitmapPixelFormat.Bgra8,
                BitmapAlphaMode.Straight,
                new BitmapTransform(),
                ExifOrientationMode.RespectExifOrientation,
                ColorManagementMode.DoNotColorManage);

                byte[] pixels = pix.DetachPixelData();
                WriteableBitmap Bmp = new WriteableBitmap((int)decoder.OrientedPixelWidth, (int)decoder.OrientedPixelHeight);
                Stream pixStream = Bmp.PixelBuffer.AsStream();
                pixStream.Write(pixels, 0, (int)(decoder.OrientedPixelWidth * decoder.OrientedPixelHeight * 4));

                return Bmp;
            }
        }
コード例 #14
0
        private async System.Threading.Tasks.Task <StorageFile> saveImageToFileAsync(RandomAccessStreamReference img)
        {
            var imgstream = await img.OpenReadAsync();

            BitmapImage bitmap = new BitmapImage();

            bitmap.SetSource(imgstream);
            Windows.UI.Xaml.Media.Imaging.WriteableBitmap src = new Windows.UI.Xaml.Media.Imaging.WriteableBitmap(bitmap.PixelWidth, bitmap.PixelHeight);
            src.SetSource(imgstream);
            Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(imgstream);

            Windows.Graphics.Imaging.PixelDataProvider pxprd = await decoder.GetPixelDataAsync(Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8, Windows.Graphics.Imaging.BitmapAlphaMode.Straight, new Windows.Graphics.Imaging.BitmapTransform(), Windows.Graphics.Imaging.ExifOrientationMode.RespectExifOrientation, Windows.Graphics.Imaging.ColorManagementMode.DoNotColorManage);

            byte[]        buffer = pxprd.DetachPixelData();
            StorageFolder folder = ApplicationData.Current.LocalFolder;
            StorageFile   file   = await folder.CreateFileAsync(img.GetHashCode() + "clipboardSaved" + ".png",
                                                                CreationCollisionOption.ReplaceExisting);

            using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite)) {
                var encoder = await Windows.Graphics.Imaging.BitmapEncoder.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.PngEncoderId, fileStream);

                encoder.SetPixelData(Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8, Windows.Graphics.Imaging.BitmapAlphaMode.Straight, decoder.PixelWidth, decoder.PixelHeight, decoder.DpiX, decoder.DpiY, buffer);
                await encoder.FlushAsync();
            }
            return(file);
        }
コード例 #15
0
        public async Task<BitmapSource> LoadImageAsync(Stream imageStream, Uri uri)
        {
            if (imageStream == null)
            {
                return null;
            }

            var stream = new InMemoryRandomAccessStream();
            imageStream.CopyTo(stream.AsStreamForWrite());
            stream.Seek(0);

            BitmapImage bitmap = new BitmapImage();
            await bitmap.SetSourceAsync(stream);

            // convert to a writable bitmap so we can get the PixelBuffer back out later...
            // in case we need to edit and/or re-encode the image.
            WriteableBitmap bmp = new WriteableBitmap(bitmap.PixelHeight, bitmap.PixelWidth);
            stream.Seek(0);
            bmp.SetSource(stream);

            List<Byte> allBytes = new List<byte>();
            byte[] buffer = new byte[4000];
            int bytesRead = 0;
            while ((bytesRead = await imageStream.ReadAsync(buffer, 0, 4000)) > 0)
            {
                allBytes.AddRange(buffer.Take(bytesRead));
            }

            DataContainerHelper.Instance.WriteableBitmapToStorageFile(bmp, uri);

            return bmp;
        }
コード例 #16
0
ファイル: MainPage.xaml.cs プロジェクト: forehalo/UWP-dev
 private async void OnClick(object sender, RoutedEventArgs e)
 {
     Button btn = sender as Button;
     btn.IsEnabled = false;
     // 项目中的图像文件
     Uri gifUri = new Uri("ms-appx:///Assets/1.gif");
     StorageFile gifFile = await StorageFile.GetFileFromApplicationUriAsync(gifUri);
     using (IRandomAccessStream inputStream = await gifFile.OpenReadAsync()) // 打开文件流
     {
         // 创建图像解码器实例
         BitmapDecoder decoder = await BitmapDecoder.CreateAsync(BitmapDecoder.GifDecoderId, inputStream);
         // 获取图像文件中的总帧数
         uint frameCount = decoder.FrameCount;
         // 分别读取各个帧中的图像,并添加到 ListView 控件中
         for(uint n = 0; n < frameCount; ++n)
         {
             BitmapFrame curFrame = await decoder.GetFrameAsync(n);
             // 获取图像的像素数据
             // 在获取数据时,对图像进行变换处理
             // 将宽度和高度变为原来的 1/3
             BitmapTransform btf = new BitmapTransform();
             btf.ScaledWidth = curFrame.PixelWidth / 3;
             btf.ScaledHeight = curFrame.PixelHeight / 3;
             var pxprd = await curFrame.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, btf, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage);
             byte[] data = pxprd.DetachPixelData();
             // 创建内存位图图像
             WriteableBitmap bmp = new WriteableBitmap((int)btf.ScaledWidth, (int)btf.ScaledHeight);
             data.CopyTo(bmp.PixelBuffer);
             lvimgs.Items.Add(bmp);
         }
     }
     btn.IsEnabled = true;
 }
コード例 #17
0
        public static void BlitBlock(this WriteableBitmap target, int targetVerticalOffset, WriteableBitmap source, int sourceVerticalOffset, int verticalBlockHeight, bool autoInvalidate = false)
        {
            if (source.PixelWidth != target.PixelWidth)
            {
                throw new ArgumentException(
                    "BlitBlock only supports copying blocks of pixels between bitmaps of equal size.",
                    "source");
            }

            if (sourceVerticalOffset + verticalBlockHeight > source.PixelHeight ||
                targetVerticalOffset + verticalBlockHeight > target.PixelHeight ||
                verticalBlockHeight <= 0)
            {
                throw new ArgumentException();
            }

            var copiedBytes =
                new byte[4 * source.PixelWidth * verticalBlockHeight];
            var inputStream = source.PixelBuffer.AsStream();
            inputStream.Seek(4 * source.PixelWidth * sourceVerticalOffset, SeekOrigin.Begin);
            inputStream.Read(copiedBytes, 0, copiedBytes.Length);

            var outputStream = target.PixelBuffer.AsStream();
            outputStream.Seek(4 * target.PixelWidth * targetVerticalOffset, SeekOrigin.Begin);
            outputStream.Write(copiedBytes, 0, copiedBytes.Length);

            if (autoInvalidate)
            {
                target.Invalidate();
            }
        }
コード例 #18
0
 private static async Task<Color> fromBitmap(WriteableBitmap bitmap)
 {
     int width = bitmap.PixelWidth;
     int height = bitmap.PixelHeight;
     pixels = new Color[width * height];
     return await GetPixels(bitmap, pixels, width, height);
 }
コード例 #19
0
ファイル: FlagFactory.cs プロジェクト: IcePlus/KidsPainter
        public FlagFactory()
        {
            /*
             * CurrentPenStyle = 0   不画东西
            * CurrentPenStyle = 1   油画棒风格
            * CurrentPenStyle = 2   水彩风格
            * CurrentPenStyle = 3   印章风格
            * CurrentPenStyle = 4   橡皮擦
             */

            CurrentPenStyle = 0;
            CurrentPenColor = "";
            CurrentOpacity = 100;

            ScreenHeight = Window.Current.Bounds.Height;
            ScreenWidth = Window.Current.Bounds.Width;
            pointerDictionary = new Dictionary<uint, Polyline>();
            MoveOut = false;
            Pressed = false;
            ReleaseAtOut = false;
            IsDragingPic = false;
            DragPic = null;
            IsGetScreenSucccess = false;
            strContent = "";
            PainterHeight = ScreenHeight - 180;
            PainterWidth = ScreenWidth - 80;
            BitmapOutput = new WriteableBitmap((int)PainterWidth,(int)PainterHeight);
        }
コード例 #20
0
        private static unsafe WriteableBitmap ToWriteableBitmap(this BitmapHolder holder)
        {
            var writeableBitmap = new WriteableBitmap(holder.Width, holder.Height);

            using (var stream = writeableBitmap.PixelBuffer.AsStream())
            {
                int length = holder.Pixels.Length;

                var buffer = new byte[length * 4];
                fixed (int* srcPtr = holder.Pixels)
                {
                    var b = 0;
                    for (var i = 0; i < length; i++, b += 4)
                    {
                        var p = srcPtr[i];
                        buffer[b + 3] = (byte)((p >> 24) & 0xff);
                        buffer[b + 2] = (byte)((p >> 16) & 0xff);
                        buffer[b + 1] = (byte)((p >> 8) & 0xff);
                        buffer[b + 0] = (byte)(p & 0xff);
                    }
                    stream.Write(buffer, 0, length * 4);
                }

            }

            return writeableBitmap;
        }
コード例 #21
0
ファイル: BitmapCapture.cs プロジェクト: L-SEG/Vitruvius
        /// <summary>
        /// Saves the specified bitmap to the specified location.
        /// </summary>
        /// <param name="source">The source bitmap image.</param>
        /// <param name="destination">The destination storage file for the image. JPEG, PNG, GIF, BMP and TIFF formats are supported.</param>
        /// <param name="width">The width of the image file.</param>
        /// <param name="height">The height of the image file.</param>
        /// <returns>True if the bitmap file was successfully saved. False otherwise.</returns>
        public async Task<bool> Save(WriteableBitmap source, StorageFile destination, int width, int height)
        {
            if (source == null || destination == null) return false;

            try
            {
                Guid encoderID = GetEncoderId(destination);

                using (IRandomAccessStream stream = await destination.OpenAsync(FileAccessMode.ReadWrite))
                {
                    Stream pixelStream = source.PixelBuffer.AsStream();
                    byte[] pixels = new byte[pixelStream.Length];
                    await pixelStream.ReadAsync(pixels, 0, pixels.Length);

                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderID, stream);
                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)source.PixelWidth, (uint)source.PixelHeight, Constants.DPI, Constants.DPI, pixels);

                    if (source.PixelWidth != width || source.PixelHeight != height)
                    {
                        encoder.BitmapTransform.ScaledWidth = (uint)width;
                        encoder.BitmapTransform.ScaledHeight = (uint)height;
                    }

                    await encoder.FlushAsync();
                }

                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            return false;
        }
コード例 #22
0
ファイル: WPOCRService.cs プロジェクト: SamirHafez/Nutrition
        async Task<string> OCRAsync(byte[] buffer, uint width, uint height)
        {
            var bitmap = new WriteableBitmap((int)width, (int)height);

            var memoryStream = new MemoryStream(buffer);
            await bitmap.SetSourceAsync(memoryStream.AsRandomAccessStream());

            if (bitmap.PixelHeight < 40 ||
                bitmap.PixelHeight > 2600 ||
                bitmap.PixelWidth < 40 ||
                bitmap.PixelWidth > 2600)
                bitmap = await ResizeImage(bitmap, (uint)(bitmap.PixelWidth * .7), (uint)(bitmap.PixelHeight * .7));

            var ocrResult = await ocrEngine.RecognizeAsync((uint)bitmap.PixelHeight, (uint)bitmap.PixelWidth, bitmap.PixelBuffer.ToArray());

            if (ocrResult.Lines != null)
            {
                var extractedText = new StringBuilder();

                foreach (var line in ocrResult.Lines)
                {
                    foreach (var word in line.Words)
                        extractedText.Append(word.Text + " ");
                    extractedText.Append(Environment.NewLine);
                }

                return extractedText.ToString();
            }

            return null;
        }
コード例 #23
0
ファイル: WPOCRService.cs プロジェクト: SamirHafez/Nutrition
 async Task<WriteableBitmap> ResizeImage(WriteableBitmap baseWriteBitmap, uint width, uint height)
 {
     Stream stream = baseWriteBitmap.PixelBuffer.AsStream();
     byte[] pixels = new byte[(uint)stream.Length];
     await stream.ReadAsync(pixels, 0, pixels.Length);
     var inMemoryRandomStream = new InMemoryRandomAccessStream();
     var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, inMemoryRandomStream);
     encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)baseWriteBitmap.PixelWidth, (uint)baseWriteBitmap.PixelHeight, 96, 96, pixels);
     await encoder.FlushAsync();
     var transform = new BitmapTransform
     {
         ScaledWidth = width,
         ScaledHeight = height
     };
     inMemoryRandomStream.Seek(0);
     var decoder = await BitmapDecoder.CreateAsync(inMemoryRandomStream);
     var pixelData = await decoder.GetPixelDataAsync(
                     BitmapPixelFormat.Bgra8,
                     BitmapAlphaMode.Straight,
                     transform,
                     ExifOrientationMode.IgnoreExifOrientation,
                     ColorManagementMode.DoNotColorManage);
     var sourceDecodedPixels = pixelData.DetachPixelData();
     var inMemoryRandomStream2 = new InMemoryRandomAccessStream();
     var encoder2 = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, inMemoryRandomStream2);
     encoder2.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, width, height, 96, 96, sourceDecodedPixels);
     await encoder2.FlushAsync();
     inMemoryRandomStream2.Seek(0);
     var bitmap = new WriteableBitmap((int)width, (int)height);
     await bitmap.SetSourceAsync(inMemoryRandomStream2);
     return bitmap;
 }
コード例 #24
0
ファイル: MainPage.xaml.cs プロジェクト: noa99kee/K4W2-Book
        protected override void OnNavigatedTo( NavigationEventArgs e )
        {
            base.OnNavigatedTo( e );

            try {
                // Kinectを開く
                kinect = KinectSensor.GetDefault();
                kinect.Open();

                // 表示のためのデータを作成
                depthFrameDesc = kinect.DepthFrameSource.FrameDescription;

                // Depthリーダーを開く
                depthFrameReader = kinect.DepthFrameSource.OpenReader();
                depthFrameReader.FrameArrived += depthFrameReader_FrameArrived;

                // 表示のためのデータ
                depthBitmap = new WriteableBitmap( depthFrameDesc.Width,
                                                   depthFrameDesc.Height );
                ImageDepth.Source = depthBitmap;

                depthBuffer = new ushort[depthFrameDesc.LengthInPixels];
                depthBitmapBuffer = new byte[depthFrameDesc.LengthInPixels * 4];

                depthPoint = new Point( depthFrameDesc.Width / 2,
                                        depthFrameDesc.Height / 2 );
            }
            catch ( Exception ex ) {
                MessageDialog dlg = new MessageDialog(ex.Message);
                dlg.ShowAsync();
            }
        }
コード例 #25
0
		private async Task<FrameWithFaces> CaptureFrameAsync()
		{
			var previewProperties = mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;
			var width = (int)previewProperties.Width;
			var height = (int)previewProperties.Height;
			var videoFrame = new VideoFrame(BitmapPixelFormat.Rgba8, width, height);
			if (tempWb == null)
				tempWb = new WriteableBitmap(width, height);

			using (var currentFrame = await mediaCapture.GetPreviewFrameAsync(videoFrame))
			{
				SoftwareBitmap bitmap = currentFrame.SoftwareBitmap;
				var detector = await Windows.Media.FaceAnalysis.FaceDetector.CreateAsync();
				var supportedBitmapPixelFormats = Windows.Media.FaceAnalysis.FaceDetector.GetSupportedBitmapPixelFormats();
				var convertedBitmap = SoftwareBitmap.Convert(bitmap, supportedBitmapPixelFormats.First());
				var detectedFaces = await detector.DetectFacesAsync(convertedBitmap);

				byte[] bytes;
				bitmap.CopyToBuffer(tempWb.PixelBuffer);
				using (Stream stream = tempWb.PixelBuffer.AsStream())
				using (MemoryStream memoryStream = new MemoryStream())
				{
					stream.CopyTo(memoryStream);
					bytes = memoryStream.ToArray();
					return new FrameWithFaces
						{
							FrameData = bytes,
							FrameWidth = width,
							FrameHeight = height,
							Faces = detectedFaces.Select(f => 
								new Rect {X = f.FaceBox.X, Y = f.FaceBox.Y, Width = f.FaceBox.Width, Height = f.FaceBox.Height}).ToArray()
						};
				}
			}
		}
コード例 #26
0
ファイル: MainPage.xaml.cs プロジェクト: noa99kee/K4W2-Book
        protected override void OnNavigatedTo( NavigationEventArgs e )
        {
            base.OnNavigatedTo( e );

            try {
                // Kinectを開く
                kinect = KinectSensor.GetDefault();
                if ( kinect == null ) {
                    throw new Exception( "Kinectを開けません" );
                }

                kinect.Open();

                // 赤外線画像の情報を取得する
                infraredFrameDesc = kinect.InfraredFrameSource.FrameDescription;

                // 画像化のためのバッファを作成する
                infraredBitmapBuffer = new byte[infraredFrameDesc.LengthInPixels * 4];
                infraredBitmap = new WriteableBitmap(
                    infraredFrameDesc.Width, infraredFrameDesc.Height );
                ImageInfrared.Source = infraredBitmap;

                infraredBuffer = new ushort[infraredFrameDesc.LengthInPixels];

                // 赤外線画像リーダーを開く
                infraredFrameReader = kinect.InfraredFrameSource.OpenReader();
                infraredFrameReader.FrameArrived += infraredFrameReader_FrameArrived;
            }
            catch ( Exception ex ) {
                MessageDialog dlg = new MessageDialog( ex.Message );
                dlg.ShowAsync();
            }
        }
コード例 #27
0
        private async void RunTriangleUpdaterAsync()
        {
            do
            {
                await _triangleUpdateRequired.WaitAsync();

                if (_isLoaded)
                {
                    var wb = new WriteableBitmap(
                        (int)trianglePicker.ActualWidth,
                        (int)trianglePicker.ActualHeight);

                    var wbHue = new WriteableBitmap(
                        (int)slidersPanel.ActualWidth - 80,
                        1);

                    var wbSaturation = new WriteableBitmap(
                        (int)slidersPanel.ActualWidth - 80,
                        1);

                    var wbLightness = new WriteableBitmap(
                        (int)slidersPanel.ActualWidth - 80,
                        1);

                    var wbRed = new WriteableBitmap(
                        (int)slidersPanel.ActualWidth - 80,
                        1);

                    var wbGreen = new WriteableBitmap(
                        (int)slidersPanel.ActualWidth - 80,
                        1);

                    var wbBlue = new WriteableBitmap(
                        (int)slidersPanel.ActualWidth - 80,
                        1);

                    var color = ColorExtensions.FromHsl(hueRing.Value, 1, 0.5);

                    await Task.WhenAll(
                        wb.RenderColorPickerSaturationValueTriangleAsync(hueRing.Value),
                        wbHue.RenderColorPickerHSLHueBarAsync(1.0, 0.5),
                        wbSaturation.RenderColorPickerHSLSaturationBarAsync(hueRing.Value, 0.5),
                        wbLightness.RenderColorPickerHSLLightnessBarAsync(hueRing.Value, 0.5),
                        wbRed.RenderColorPickerRGBRedBarAsync(color.G / 255.0, color.B / 255.0),
                        wbGreen.RenderColorPickerRGBGreenBarAsync(color.R / 255.0, color.B / 255.0),
                        wbBlue.RenderColorPickerRGBBlueBarAsync(color.R / 255.0, color.G / 255.0));

                    if (_isLoaded)
                    {
                        triangleBrush.ImageSource = wb;
                        hueBackground.ImageSource = wbHue;
                        saturationBackground.ImageSource = wbSaturation;
                        lightnessBackground.ImageSource = wbLightness;
                        redBackground.ImageSource = wbRed;
                        greenBackground.ImageSource = wbGreen;
                        blueBackground.ImageSource = wbBlue;
                    }
                }
            } while (_isLoaded);
        }
コード例 #28
0
ファイル: MainModel.cs プロジェクト: jcapellman/jcMSBWN
        public async Task<bool> RegisterTile() {
            var pairedBands = await BandClientManager.Instance.GetBandsAsync();

            using (var bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0])) {
                var tiles = await bandClient.TileManager.GetTilesAsync();

                var tileCapacity = await bandClient.TileManager.GetRemainingTileCapacityAsync();

                var tileIconBitmap = new WriteableBitmap(46, 46);
                
                var tileIcon = tileIconBitmap.ToBandIcon();

                var tileGuid = Guid.NewGuid();

                var tile = new BandTile(tileGuid) { 
                    IsBadgingEnabled = true,   
                    Name = "jcMSBWN",     
                    TileIcon = tileIcon
                };

                await bandClient.TileManager.AddTileAsync(tile);
                
                _setting.WriteSetting(SETTINGS.TILE_ID, tile.TileId);
            }

            return true;
        }
コード例 #29
0
        protected override void OnNavigatedTo( NavigationEventArgs e )
        {
            base.OnNavigatedTo( e );

            try {
                // Kinectを開く
                kinect = KinectSensor.GetDefault();
                if ( kinect == null ) {
                    throw new Exception( "Kinectを開けません" );
                }

                kinect.Open();

                // カラー画像の情報を作成する(BGRAフォーマット)
                colorFrameDesc = kinect.ColorFrameSource.CreateFrameDescription( ColorImageFormat.Bgra );

                colorBitmap = new WriteableBitmap( colorFrameDesc.Width, colorFrameDesc.Height );
                ImageColor.Source = colorBitmap;

                colorBuffer = new byte[colorFrameDesc.Width * colorFrameDesc.Height * colorFrameDesc.BytesPerPixel];

                // カラーリーダーを開く
                colorFrameReader = kinect.ColorFrameSource.OpenReader();
                colorFrameReader.FrameArrived += colorFrameReader_FrameArrived;
            }
            catch ( Exception ex ) {
                MessageDialog dlg = new MessageDialog( ex.Message );
                dlg.ShowAsync();
            }
        }
コード例 #30
0
        public async static Task<WriteableBitmap> ToBitmapImageAsync(this byte[] imageBytes, Tuple<int, int> downscale)
        {
            if (imageBytes == null)
                return null;

            IRandomAccessStream image = imageBytes.AsBuffer().AsStream().AsRandomAccessStream();

            if (downscale != null && (downscale.Item1 > 0 || downscale.Item2 > 0))
            {
                image = await image.ResizeImage((uint)downscale.Item1, (uint)downscale.Item2);
            }

            using (image)
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(image);

                image.Seek(0);

                WriteableBitmap bitmap = null;

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () =>
                {
                    bitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                    bitmap.SetSource(image);
                });

                return bitmap;
            }
        }
コード例 #31
0
        public unsafe async static Task<WriteableBitmap> ToBitmapImageAsync(this BitmapHolder holder)
        {
            if (holder == null || holder.Pixels == null)
                return null;

            var writeableBitmap = new WriteableBitmap(holder.Width, holder.Height);

            using (var stream = writeableBitmap.PixelBuffer.AsStream())
            {
                int length = holder.Pixels.Length;

                var buffer = new byte[length * 4];
                fixed (int* srcPtr = holder.Pixels)
                {
                    var b = 0;
                    for (var i = 0; i < length; i++, b += 4)
                    {
                        var p = srcPtr[i];
                        buffer[b + 3] = (byte)((p >> 24) & 0xff);
                        buffer[b + 2] = (byte)((p >> 16) & 0xff);
                        buffer[b + 1] = (byte)((p >> 8) & 0xff);
                        buffer[b + 0] = (byte)(p & 0xff);
                    }
                    stream.Write(buffer, 0, length * 4);
                }

            }
            writeableBitmap.Invalidate();

            return writeableBitmap;
        }
コード例 #32
0
        LoadImageAsync(Windows.Storage.StorageFile file)
        {
            Windows.Storage.FileProperties.ImageProperties imgProp = await file.Properties.GetImagePropertiesAsync();

            using (var imgStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
            {
                var bitmap = new Windows.UI.Xaml.Media.Imaging.WriteableBitmap((int)imgProp.Width, (int)imgProp.Height);
                bitmap.SetSource(imgStream);
                return(bitmap);
            }
        }
コード例 #33
0
        /// <summary>
        /// 画像ファイル読込
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private async System.Threading.Tasks.Task LoadSampleImage(StorageFile file)
        {
            _bitmap = await LoadImageAsync(file);

            this.SampleImage.Source = _bitmap;

            // 日本語OCR
            if (_bitmap != null)
            {
                await ExtractTextAsync(_bitmap, WindowsPreview.Media.Ocr.OcrLanguage.Japanese);
            }
        }