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;
            }
        }
Ejemplo n.º 2
0
        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();
                }
            }

        }
Ejemplo n.º 3
0
        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;
        }
Ejemplo n.º 4
0
        public async Task ScanBarcodeAsync(Windows.Storage.StorageFile file)
        {
            WriteableBitmap bitmap;
            BitmapDecoder decoder;
            using (IRandomAccessStream str = await file.OpenReadAsync())
            {
                decoder = await BitmapDecoder.CreateAsync(str);
                bitmap = new WriteableBitmap(Convert.ToInt32(decoder.PixelWidth), Convert.ToInt32(decoder.PixelHeight));
                await bitmap.SetSourceAsync(str);
            }

            lock (locker)
            {                
                ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
                reader.Options.PossibleFormats = new ZXing.BarcodeFormat[] { ZXing.BarcodeFormat.CODE_128, ZXing.BarcodeFormat.QR_CODE, ZXing.BarcodeFormat.CODE_39 };
                reader.Options.TryHarder = true;
                reader.AutoRotate = true;
                var results = reader.Decode(bitmap);
                if (results == null)
                {
                    this.OnBarcodeScannCompleted(new BarcodeScanCompletedEventArgs(false, string.Empty));
                }
                else
                {
                    this.OnBarcodeScannCompleted(new BarcodeScanCompletedEventArgs(true, results.Text));
                }
            }
        }
        async Task<WriteableBitmap> SelectImageFromPicker()
        {
            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);
                bitmap.Invalidate();

                SaveImageAsync(file);

                return bitmap;
            }
            else return null;
        }
Ejemplo n.º 6
0
        private async Task<BandIcon> LoadIcon(string uri)
        {
            StorageFile imageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(uri));

            using (IRandomAccessStream fileStream = await imageFile.OpenAsync(FileAccessMode.Read))
            {
                WriteableBitmap bitmap = new WriteableBitmap(1, 1);
                await bitmap.SetSourceAsync(fileStream);
                return bitmap.ToBandIcon();
            }
        }
        private static async Task<WriteableBitmap> GetWriteableBitmap(Uri uri)
        {
            var imageFile = await StorageFile.GetFileFromApplicationUriAsync(uri);

            using (var fileStream = await imageFile.OpenAsync(FileAccessMode.Read))
            {
                var writeableBitmap = new WriteableBitmap(1, 1);
                await writeableBitmap.SetSourceAsync(fileStream);
                return writeableBitmap;
            }
        }
Ejemplo n.º 8
0
        public static async Task<WriteableBitmap> GetPictureAsync(StorageFile ImageFile)
        {

            using (IRandomAccessStream stream = await ImageFile.OpenAsync(FileAccessMode.Read))
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
                WriteableBitmap bmp = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                await bmp.SetSourceAsync(stream);
                return bmp;
            }
        }
Ejemplo n.º 9
0
        private async void GetThumbnail()
        {
            DeviceThumbnail thumb = await _information.GetGlyphThumbnailAsync();
            Stream s = thumb.AsStreamForRead();
            MemoryStream ms = new MemoryStream();
            await s.CopyToAsync(ms);
            ms.Seek(0, SeekOrigin.Begin);

            WriteableBitmap wb = new WriteableBitmap(1, 1);
            await wb.SetSourceAsync(ms.AsRandomAccessStream());
            _thumbnail = wb;
            OnPropertyChanged("Thumbnail");
        }
Ejemplo n.º 10
0
        public async void Quadraliteral(StorageFile file, IList<WF.Point> points)
        {
            var data = await FileIO.ReadBufferAsync(file);

            OpencvImageProcess opencv = new OpencvImageProcess();
            
            // create a stream from the file
            var ms = new InMemoryRandomAccessStream();
            var dw = new DataWriter(ms);
            dw.WriteBuffer(data);
            await dw.StoreAsync();
            ms.Seek(0);

            // find out how big the image is, don't need this if you already know
            var bm = new BitmapImage();
            await bm.SetSourceAsync(ms);

            // create a writable bitmap of the right size
            var wb = new WriteableBitmap(bm.PixelWidth, bm.PixelHeight);
            ms.Seek(0);

            // load the writable bitpamp from the stream
            await wb.SetSourceAsync(ms);

            Bitmap bmp = (Bitmap)wb;

            var wb1 = opencv.GetImageCorners(wb);

            wb1.Invalidate();
            //wb.Invalidate();
            // define quadrilateral's corners
            //List<IntPoint> corners = new List<IntPoint>();
            
            //foreach (var point in points)
            //{
            //    corners.Add(new IntPoint((int)point.X, (int)point.Y));
            //}
            
            //// create filter

            //var filter =
            //    new SimpleQuadrilateralTransformation(corners);
            
            //// apply the filter
            //Bitmap newImage = filter.Apply(bmp);

            //wb = (WriteableBitmap)newImage;

            var f = await this.WriteableBitmapToStorageFile(wb1, FileFormat.Jpeg);
        }
        public ReportPhoto(StorageFile file)
        {
            FilePath = file.Path;

            StorageItemThumbnail thumbnail = file.GetThumbnailAsync(ThumbnailMode.ListView).AsTask().Result;
            BitmapImage thumbnailImage = new BitmapImage();
            var ignore = thumbnailImage.SetSourceAsync(thumbnail);
            ThumbnailSource = thumbnailImage;

            StorageItemThumbnail imageAsThumbnail = file.GetScaledImageAsThumbnailAsync(ThumbnailMode.SingleItem).AsTask().Result;
            WriteableBitmap bitmap = new WriteableBitmap((int)imageAsThumbnail.OriginalWidth, (int)imageAsThumbnail.OriginalHeight);
            ignore = bitmap.SetSourceAsync(imageAsThumbnail);
            Bitmap = bitmap;
        }
Ejemplo n.º 12
0
        private async Task<StorageFile> TakePhoto()
        {
            StorageFile filestr = await USBCam.TakePhotoAsync("picture.jpg");
            Debug.WriteLine(string.Format("File name: {0}", filestr.Name));
            using (IRandomAccessStream myfileStream = await filestr.OpenAsync(FileAccessMode.Read))
            {
                WriteableBitmap bitmap = new WriteableBitmap(1, 1);

                await bitmap.SetSourceAsync(myfileStream);

                FacePhoto.Source = bitmap;
            }
            return filestr;
        }
Ejemplo n.º 13
0
        public static async Task<ImageSource> FromBase64(string base64)
        {
            // read stream
            var bytes = Convert.FromBase64String(base64);
            var image = bytes.AsBuffer().AsStream().AsRandomAccessStream();

            // decode image
            var decoder = await BitmapDecoder.CreateAsync(image);
            image.Seek(0);

            // create bitmap
            var output = new WriteableBitmap((int) decoder.PixelHeight, (int) decoder.PixelWidth);
            await output.SetSourceAsync(image);
            return output;
        }
        public async Task<object> ConvertFromEncodedStream(Stream encodedStream, int width, int height)
        {
            if (encodedStream == null)
                return null;

            var image = new WriteableBitmap(width, height);
            encodedStream.Seek(0, SeekOrigin.Begin);
            await image.SetSourceAsync(encodedStream.AsRandomAccessStream());

            return image;

            //var writeableImage = new WriteableBitmap(image.PixelWidth, image.PixelHeight);
            //image.SetSource(encodedStream.AsRandomAccessStream());
            //return writeableImage;
        }
Ejemplo n.º 15
0
		public async Task LoadImageAsync()
		{
			using (var stream = await file.OpenReadAsync())
			{
				WriteableBitmap bitmap = new WriteableBitmap(width, height);
				await bitmap.SetSourceAsync(stream);

				using (var buffer = bitmap.PixelBuffer.AsStream())
				{
					pixels = new Byte[4 * width * height];
					buffer.Read(pixels, 0, pixels.Length);
				}

				this.bitmap = bitmap;
			}
		}
Ejemplo n.º 16
0
        private async void ViewFinder_OnTapped()
        {
            ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();

            var stream = new InMemoryRandomAccessStream();

            await captureManager.CapturePhotoToStreamAsync(imageProperties, stream);

            _bitmap = new WriteableBitmap(300, 300);
            stream.Seek(0);
            await _bitmap.SetSourceAsync(stream);

            stream.Seek(0);
            var buffer = new global::Windows.Storage.Streams.Buffer((uint)stream.Size);
            stream.ReadAsync(buffer, (uint)stream.Size, InputStreamOptions.None);
            await captureManager.StopPreviewAsync();
        }
        public async static Task<WriteableBitmap> ToBitmapImageAsync(this Stream imageStream, Tuple<int, int> downscale, bool downscaleDipUnits, InterpolationMode mode, ImageInformation imageInformation = null)
        {
            if (imageStream == null)
                return null;

            using (IRandomAccessStream image = imageStream.AsRandomAccessStream())
            {
                if (downscale != null && (downscale.Item1 > 0 || downscale.Item2 > 0))
                {
                    using (var downscaledImage = await image.ResizeImage(downscale.Item1, downscale.Item2, mode, downscaleDipUnits, imageInformation).ConfigureAwait(false))
                    {
                        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(downscaledImage);
                        downscaledImage.Seek(0);
                        WriteableBitmap resizedBitmap = null;

                        await MainThreadDispatcher.Instance.PostAsync(async () =>
                        {
                            resizedBitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                            await resizedBitmap.SetSourceAsync(downscaledImage);
                        });

                        return resizedBitmap;
                    }
                }
                else
                {
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(image);
                    image.Seek(0);
                    WriteableBitmap bitmap = null;

                    if (imageInformation != null)
                    {
                        imageInformation.SetCurrentSize((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                        imageInformation.SetOriginalSize((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                    }

                    await MainThreadDispatcher.Instance.PostAsync(async () =>
                    {
                        bitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                        await bitmap.SetSourceAsync(image);
                    });

                    return bitmap;
                }
            }
        }
Ejemplo n.º 18
0
        public static async Task<WriteableBitmap> ToWriteableBitmapAsync(this Stream stream)
        {
            var randomAccessStream = stream.AsRandomAccessStream();
            var decoder = await BitmapDecoder.CreateAsync(randomAccessStream);

            // Get the first frame from the decoder
            var frame = await decoder.GetFrameAsync(0);

            var wid = (int) frame.PixelWidth;
            var hgt = (int) frame.PixelHeight;

            var target = new WriteableBitmap(wid, hgt);

            randomAccessStream.Seek(0);
            await target.SetSourceAsync(randomAccessStream);
            return target;
        }
Ejemplo n.º 19
0
        private async Task OnHearbeat(CameraHeartBeat heartbeat)
        {
            await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
            {
                var cameras = (IEnumerable<RemoteCameraModel>) Cameras.Source;
                var camera = cameras.FirstOrDefault(x => x.IPAddress.ToString() == heartbeat.CameraId);

                if (camera != null)
                {
                    var decoder = await BitmapDecoder.CreateAsync(heartbeat.ViewBuffer.AsStream().AsRandomAccessStream());
                    var f = await decoder.GetFrameAsync(0);
                    var bmp = new WriteableBitmap((int) f.PixelWidth, (int) f.PixelHeight);
                    await bmp.SetSourceAsync(heartbeat.ViewBuffer.AsStream().AsRandomAccessStream());
                    camera.View.Value = bmp;
                }
            });
        }
Ejemplo n.º 20
0
        public async Task<WriteableBitmap> CaptureJpegImageAsync()
        {
            var bitmap      = new WriteableBitmap(400,300);

            using (var memoryStream = new InMemoryRandomAccessStream())
            {
                var file = await Windows.Storage.KnownFolders.PicturesLibrary.CreateFileAsync(IMAGECAPTURE_FILENAME, Windows.Storage.CreationCollisionOption.ReplaceExisting);

                await _exceptionHandler.Run(async () =>
                {
                    await _mediaCapture.CapturePhotoToStorageFileAsync(_imageEncodingProperties, file);
                    var photoStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
                    await bitmap.SetSourceAsync(photoStream);
                });
            }
            return bitmap;
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Scales the image in the given memory stream.
        /// </summary>
        /// <param name="originalStream">The original image stream to scale.</param>
        /// <param name="originalResolutionWidth">The original width.</param>
        /// <param name="originalResolutionHeight">The original height.</param>
        /// <param name="scaledStream">Stream where the scaled image is stored.</param>
        /// <param name="scaleWidth">The target width.</param>
        /// <param name="scaleHeight">The target height.</param>
        /// <returns></returns>
        public static async Task ScaleImageStreamAsync(MemoryStream originalStream,
                                                       int originalResolutionWidth,
                                                       int originalResolutionHeight,
                                                       MemoryStream scaledStream,
                                                       int scaleWidth,
                                                       int scaleHeight)
        {
            System.Diagnostics.Debug.WriteLine(DebugTag + "ScaleImageStreamAsync() ->");

            // Create a bitmap containing the full resolution image
            var bitmap = new WriteableBitmap(originalResolutionWidth, originalResolutionHeight);
            originalStream.Seek(0, SeekOrigin.Begin);
            await bitmap.SetSourceAsync(originalStream.AsRandomAccessStream());

            /* Construct a JPEG encoder with the newly created
             * InMemoryRandomAccessStream as target
             */
            IRandomAccessStream previewResolutionStream = new InMemoryRandomAccessStream();
            previewResolutionStream.Size = 0;
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(
                BitmapEncoder.JpegEncoderId, previewResolutionStream);

            // Copy the full resolution image data into a byte array
            Stream pixelStream = bitmap.PixelBuffer.AsStream();
            var pixelArray = new byte[pixelStream.Length];
            await pixelStream.ReadAsync(pixelArray, 0, pixelArray.Length);

            // Set the scaling properties
            encoder.BitmapTransform.ScaledWidth = (uint)scaleWidth;
            encoder.BitmapTransform.ScaledHeight = (uint)scaleHeight;
            encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
            encoder.IsThumbnailGenerated = true;

            // Set the image data and the image format setttings to the encoder
            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                (uint)originalResolutionWidth, (uint)originalResolutionHeight,
                96.0, 96.0, pixelArray);

            await encoder.FlushAsync();
            previewResolutionStream.Seek(0);
            await previewResolutionStream.AsStream().CopyToAsync(scaledStream);

            System.Diagnostics.Debug.WriteLine(DebugTag + "<- ScaleImageStreamAsync()");
        }
Ejemplo n.º 22
0
        public async static Task<WriteableBitmap> ToBitmapImageAsync(this byte[] imageBytes, Tuple<int, int> downscale, bool downscaleDipUnits, InterpolationMode mode)
        {
            if (imageBytes == null)
                return null;

            using (var imageStream = imageBytes.AsBuffer().AsStream())
            using (IRandomAccessStream image = imageStream.AsRandomAccessStream())
            {
                if (downscale != null && (downscale.Item1 > 0 || downscale.Item2 > 0))
                {
                    using (var downscaledImage = await image.ResizeImage(downscale.Item1, downscale.Item2, mode, downscaleDipUnits).ConfigureAwait(false))
                    {
                        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(downscaledImage);
                        downscaledImage.Seek(0);
                        WriteableBitmap resizedBitmap = null;

                        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, async () =>
                        {
                            resizedBitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                            await resizedBitmap.SetSourceAsync(downscaledImage);
                        });

                        return resizedBitmap;
                    }
                }
                else
                {
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(image);
                    image.Seek(0);
                    WriteableBitmap bitmap = null;

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

                    return bitmap;
                }
            }
        }
Ejemplo n.º 23
0
        protected async Task<WriteableBitmap> GetImage(string url)
        {
            try
            {
                IBuffer buffer = await BaseService.SendGetRequestAsBytes(url);
                if (buffer != null)
                {
                    BitmapImage bi = new BitmapImage();
                    WriteableBitmap wb = null; Stream stream2Write;
                    using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
                    {

                        stream2Write = stream.AsStreamForWrite();

                        await stream2Write.WriteAsync(buffer.ToArray(), 0, (int)buffer.Length);

                        await stream2Write.FlushAsync();
                        stream.Seek(0);

                        await bi.SetSourceAsync(stream);

                        wb = new WriteableBitmap(bi.PixelWidth, bi.PixelHeight);
                        stream.Seek(0);
                        await wb.SetSourceAsync(stream);

                        return wb;
                    }
                }
                else
                {
                    return null;
                }
            }
            catch
            {
                return null;
            }
        }
Ejemplo n.º 24
0
        private async Task<Stream> CreateThumb(Stream orgStm, int width, int height, string filePath) {

            var ras = orgStm.AsRandomAccessStream();
            var wb = new WriteableBitmap(width, height);
            ras.Seek(0);
            await wb.SetSourceAsync(ras);

            var stm = wb.PixelBuffer.AsStream();
            var bytes = await stm.GetBytes();

            using (var fs = await FileManager.Instance.Value.OpenFile(filePath)) {
                //BitmapEncoder 无法写入 MemoryStream
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(
                    BitmapEncoder.JpegEncoderId,
                    fs);

                encoder.BitmapTransform.ScaledWidth = (uint)width;
                encoder.BitmapTransform.ScaledHeight = (uint)height;
                //encoder.BitmapTransform.Rotation = BitmapRotation.Clockwise90Degrees;

                encoder.SetPixelData(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Straight,
                    (uint)wb.PixelWidth,
                    (uint)wb.PixelHeight,
                    96.0,
                    96.0,
                    bytes);

                await encoder.FlushAsync();
                return fs.CloneStream().AsStream();
            }
        }
        private async void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            (sender as AppBarButton).Icon.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 169, 3));
            (sender as AppBarButton).Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 169, 3));
            AppBarButton bar = sender as AppBarButton;
            foreach (var item in barList)
            {
                if (item.Equals(bar))
                {
                    item.Icon.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 169, 3));
                    item.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 169, 3));
                }
                else
                {
                    item.Icon.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
                    item.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
                }
            }
            if (WB_CapturedImage == null)
            {
                StorageFile file = await StorageFile.GetFileFromPathAsync(filePath);
                BitmapImage image1 = new BitmapImage();
                using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
                {
                    image1.SetSource(fileStream);
                    WB_CapturedImage = new WriteableBitmap((int)image1.PixelWidth, (int)image1.PixelHeight);
                }
                using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
                {

                    await WB_CapturedImage.SetSourceAsync(fileStream);
                    m_displayHeightNonScaled = WB_CapturedImage.PixelHeight;
                    m_displayWidthNonScaled = WB_CapturedImage.PixelWidth;
                }
            }
            if (clippingGrid.Visibility == Visibility.Collapsed)
            {
                ResetClippingGrid();
            }
        }
        private async void SaveTextPicture()
        {
            try
            {
                StorageFolder savedPics = KnownFolders.PicturesLibrary;
                IReadOnlyList<StorageFolder> folders = await savedPics.GetFoldersAsync();
                foreach (var item in folders)
                {
                    if (item.Name.Equals("Camera Roll"))
                    {
                        savedPics = item;
                        break;
                    }
                }
                string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".png";
                // 1、在位图中呈现UI元素
                RenderTargetBitmap rtb = new RenderTargetBitmap();
                await rtb.RenderAsync(this.textCanvas);
                // 提取像素数据
                IBuffer buffer = await rtb.GetPixelsAsync();

                // 创建新文件
                StorageFile newFile = await savedPics.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
                using (IRandomAccessStream streamOut = await newFile.OpenAsync(FileAccessMode.ReadWrite))
                {

                    // 实例化编码器
                    BitmapEncoder pngEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, streamOut);
                    // 写入像素数据
                    byte[] data = buffer.ToArray();
                    pngEncoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                            BitmapAlphaMode.Straight,
                                            (uint)rtb.PixelWidth,
                                            (uint)rtb.PixelHeight,
                                            96d, 96d, data);
                    await pngEncoder.FlushAsync();
                    streamOut.Dispose();
                }
                //StorageFile file = await StorageFile.GetFileFromPathAsync(newFile.Path);
                //StorageFile newFile1 = await savedPics.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists); 
                using (IRandomAccessStream streamOut = await newFile.OpenAsync(FileAccessMode.Read))
                {
                    BitmapImage image1 = new BitmapImage();
                    image1.SetSource(streamOut);
                    image.Source = image1;
                    WB_CapturedImage = new WriteableBitmap((int)image1.PixelWidth, (int)image1.PixelHeight);
                    streamOut.Dispose();
                }
                //WB_CapturedImage.SetSource(streamOut);
                using (IRandomAccessStream streamOut = await newFile.OpenAsync(FileAccessMode.Read))
                {
                    await WB_CapturedImage.SetSourceAsync(streamOut);
                    m_displayHeightNonScaled = WB_CapturedImage.PixelHeight;
                    m_displayWidthNonScaled = WB_CapturedImage.PixelWidth;
                    //image.Source = WB_CapturedImage;
                    streamOut.Dispose();
                }
                //textCanvas.ClearValue(BackgroundProperty);
                textCanvas.Width = image.ActualWidth;
                textCanvas.Height = image.ActualHeight;
            }
            catch (Exception e)
            {
                textCanvas.ClearValue(BackgroundProperty);
#if DEBUG
                System.Diagnostics.Debug.WriteLine(e.Message);
#endif
            }
        }
        private async void SaveInkPicture()
        {
            if (ink.Width == 0)
            {
                return;
            }
             //ink.Width = WB_CapturedImage.PixelWidth;
             //ink.Height = WB_CapturedImage.PixelHeight;
             ((App)App.Current).SyncStrokeEx(strokeMapping, ink.InkPresenter.StrokeContainer, ink.Width, true);
            CanvasDevice device = CanvasDevice.GetSharedDevice();
            //CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, WB_CapturedImage.PixelWidth, WB_CapturedImage.PixelHeight, 96);
            CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (float)ink.Width, (float)ink.Height, 96);
            using (var ds = renderTarget.CreateDrawingSession())
            {
                ds.Clear(Color.FromArgb(0, 255, 255, 255));
                ds.DrawInk(ink.InkPresenter.StrokeContainer.GetStrokes());
            }
            StorageFolder savedPics = KnownFolders.PicturesLibrary;
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".png";
            StorageFile file = await savedPics.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
            using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Png, 1f);
            }
            using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
            {
                //image.SetSource(fileStream);
                WriteableBitmap InkImage = new WriteableBitmap(WB_CapturedImage.PixelWidth, WB_CapturedImage.PixelHeight);
                await InkImage.SetSourceAsync(fileStream);
                imageInk.Source = InkImage;
                imageInk.Visibility = Visibility.Visible;
                ink.InkPresenter.StrokeContainer.Clear();
                ink.Visibility = Visibility.Collapsed;
            }

            RenderTargetBitmap rtb = new RenderTargetBitmap();
            await rtb.RenderAsync(this.imagePanel);
            // 提取像素数据
            IBuffer buffer = await rtb.GetPixelsAsync();

            // 获取文件流
            IRandomAccessStream streamOut = await file.OpenAsync(FileAccessMode.ReadWrite);
            // 实例化编码器
            BitmapEncoder pngEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, streamOut);
            //重写writeablebitmap
            WB_CapturedImage = new WriteableBitmap((int)rtb.PixelWidth, (int)rtb.PixelHeight);
            // 写入像素数据
            byte[] data = buffer.ToArray();
            pngEncoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                    BitmapAlphaMode.Straight,
                                    (uint)rtb.PixelWidth,
                                    (uint)rtb.PixelHeight,
                                    96d, 96d, data);
            await pngEncoder.FlushAsync();
            streamOut.Dispose();

            ink.Visibility = Visibility.Visible;
            imageInk.Visibility = Visibility.Collapsed;

            using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
            {
                await WB_CapturedImage.SetSourceAsync(fileStream);
                image.Source = WB_CapturedImage;
            }

            //var bmp = new RenderTargetBitmap();          
            //await bmp.RenderAsync(ink);
            //StorageFolder savedPics = KnownFolders.PicturesLibrary;
            //string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".png";
            //StorageFile file = await savedPics.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
            //// Saving to file.  
            //using (var stream = await file.OpenStreamForWriteAsync())
            //{
            //    // Initialization.  
            //    var pixelBuffer = await bmp.GetPixelsAsync();
            //    var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
            //    // convert stream to IRandomAccessStream  
            //    var randomAccessStream = stream.AsRandomAccessStream();
            //    // encoding to PNG  
            //    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, randomAccessStream);
            //    // Finish saving  
            //    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)bmp.PixelWidth,
            //               (uint)bmp.PixelHeight, logicalDpi, logicalDpi, pixelBuffer.ToArray());
            //    // Flush encoder.  
            //    await encoder.FlushAsync();
            //    filePath = file.Path;
            //}
        }
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                StorageFile file = await StorageFile.GetFileFromPathAsync(filePath);
                BitmapImage image1 = new BitmapImage();
                using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
                {
                    image1.SetSource(fileStream);
                    WB_CapturedImage = new WriteableBitmap((int)image1.PixelWidth, (int)image1.PixelHeight);
                }
                using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
                {

                    await WB_CapturedImage.SetSourceAsync(fileStream);
                    m_displayHeightNonScaled = WB_CapturedImage.PixelHeight;
                    m_displayWidthNonScaled = WB_CapturedImage.PixelWidth;
                }

            }
            catch (Exception ex)
            {
#if DEBUG
                System.Diagnostics.Debug.WriteLine(ex.Message);
#endif
            }
        }
Ejemplo n.º 29
0
        private static async Task<WriteableBitmap> LoadImage(string filePath)
        {
            WriteableBitmap writeableBitmap=null;

            StorageFile storageFile =
                 await StorageFile.GetFileFromApplicationUriAsync(new Uri(filePath));
            using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.Read))
            {
                BitmapImage bitmapImage = new BitmapImage();
                await bitmapImage.SetSourceAsync(fileStream);

                writeableBitmap =
                    new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
                fileStream.Seek(0);
                await writeableBitmap.SetSourceAsync(fileStream);

                
            }

            return writeableBitmap;
        }
Ejemplo n.º 30
0
 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;
 }