/// <summary>
        /// Asynchronously saves the <paramref name="photo" /> given to the camera roll album.
        /// </summary>
        /// <param name="photo">Photo to save.</param>
        /// <returns>Image with thumbnail.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="photo"/> is <see langword="null"/>.</exception>
        public async Task <IThumbnailedImage> SaveResultToCameraRollAsync(ICapturedPhoto photo)
        {
            if (photo == null)
            {
                throw new ArgumentNullException("photo");
            }

            Tracing.Trace("StorageService: Trying to save picture to the Camera Roll.");

            Picture cameraRollPicture;
            string  name = this.GeneratePhotoName();

            using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
            {
                // Convert image to JPEG format and rotate in accordance with the original photo orientation.
                Tracing.Trace("StorageService: Converting photo to JPEG format. Size: {0}x{1}, Rotation: {2}", photo.Width, photo.Height, photo.Rotation);
                byte[] pixelData = await photo.DetachPixelDataAsync();

                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

                encoder.BitmapTransform.Rotation = photo.Rotation;
                encoder.BitmapTransform.Flip     = photo.Flip;
                encoder.IsThumbnailGenerated     = true;

                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, photo.Width, photo.Height, Constants.DefaultDpiX, Constants.DefaultDpiY, pixelData);
                await encoder.FlushAsync();

                cameraRollPicture = this.lazyMediaLibrary.Value.SavePictureToCameraRoll(name, stream.AsStream());
            }

            Tracing.Trace("StorageService: Saved to Camera Roll as {0}", name);

            return(new MediaLibraryThumbnailedImage(cameraRollPicture));
        }
        private static async Task <StorageFile> WriteableBitmapToStorageFile(WriteableBitmap WB, string fileName, string folderName)
        {
            Guid BitmapEncoderGuid = BitmapEncoder.PngEncoderId;

            StorageFolder localFolder        = Windows.Storage.ApplicationData.Current.LocalFolder;
            StorageFolder createFlatUIFolder = await localFolder.CreateFolderAsync((string)ApplicationData.Current.LocalSettings.Values["ModernFolder"], CreationCollisionOption.OpenIfExists);

            StorageFolder desegnatedFolder = await createFlatUIFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists);

            var bmif = await desegnatedFolder.CreateFileAsync($"{fileName}.temp", CreationCollisionOption.ReplaceExisting);

            using (IRandomAccessStream stream = await bmif.OpenAsync(FileAccessMode.ReadWrite))
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoderGuid, stream);

                Stream pixelStream = WB.PixelBuffer.AsStream();
                byte[] pixels      = new byte[pixelStream.Length];
                await pixelStream.ReadAsync(pixels, 0, pixels.Length);

                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                                     (uint)WB.PixelWidth,
                                     (uint)WB.PixelHeight,
                                     96.0,
                                     96.0,
                                     pixels);
                await encoder.FlushAsync();
            }
            return(bmif);
        }
示例#3
0
        /// <summary>
        /// Asynchronously saves all the album arts in the library.
        /// </summary>
        /// <param name="Data">ID3 tag of the song to get album art data from.</param>
        public async void SaveImages(ID3v2 Data, Mediafile file)
        {
            var albumartFolder = ApplicationData.Current.LocalFolder;
            //Debug.Write(albumartFolder.Path);
            var md5Path = (file.Album + file.LeadArtist).ToLower().ToSha1();

            if (!File.Exists(albumartFolder.Path + @"\AlbumArts\" + md5Path + ".jpg"))
            {
                var albumart = await albumartFolder.CreateFileAsync(@"AlbumArts\" + md5Path + ".jpg", CreationCollisionOption.FailIfExists);

                using (var albumstream = await albumart.OpenStreamForWriteAsync())
                {
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(Data.AttachedPictureFrames[0].Data.AsRandomAccessStream());

                    WriteableBitmap bmp = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                    await bmp.SetSourceAsync(Data.AttachedPictureFrames[0].Data.AsRandomAccessStream());

                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, albumstream.AsRandomAccessStream());

                    var    pixelStream = bmp.PixelBuffer.AsStream();
                    byte[] pixels      = new byte[bmp.PixelBuffer.Length];
                    await pixelStream.ReadAsync(pixels, 0, pixels.Length);

                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)bmp.PixelWidth, (uint)bmp.PixelHeight, 96, 96, pixels);
                    await encoder.FlushAsync();

                    pixelStream.Dispose();
                }
            }
        }
示例#4
0
        public static async Task <string> SaveStreamAsync(IRandomAccessStream streamToSave, uint width, uint height, string fileName)
        {
            FolderPicker folderPicker = new FolderPicker();

            folderPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            folderPicker.ViewMode = PickerViewMode.List;
            folderPicker.FileTypeFilter.Add(".jpg");
            folderPicker.FileTypeFilter.Add(".jpeg");
            folderPicker.FileTypeFilter.Add(".png");
            StorageFolder newFolder = await folderPicker.PickSingleFolderAsync();

            StorageFile destination = await newFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

            BitmapTransform transform = new BitmapTransform();

            BitmapDecoder bmpDecoder = await BitmapDecoder.CreateAsync(streamToSave);

            PixelDataProvider pixelData = await bmpDecoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);

            using (var destFileStream = await destination.OpenAsync(FileAccessMode.ReadWrite))
            {
                BitmapEncoder bmpEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destFileStream);

                bmpEncoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, width, height, 300, 300, pixelData.DetachPixelData());
                await bmpEncoder.FlushAsync();
            }
            return(destination.Path);
        }
示例#5
0
        public static async Task <FileUpdateStatus> WriteToStorageFile(this WriteableBitmap bitmap, Guid encoderId, StorageFile file)
        {
            StorageFile sFile = file;

            if (sFile != null)
            {
                CachedFileManager.DeferUpdates(sFile);

                using (var fileStream = await sFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, 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);
        }
示例#6
0
        private async void SaveImageFile(WriteableBitmap finalImage)
        {
            // Set up and launch the Save Picker
            FileSavePicker fileSavePicker = new FileSavePicker();

            fileSavePicker.FileTypeChoices.Add("PNG", new string[] { ".png" });
            StorageFile savefile = await fileSavePicker.PickSaveFileAsync();

            if (savefile == null)
            {
                return;
            }
            IRandomAccessStream stream = await savefile.OpenAsync(FileAccessMode.ReadWrite);

            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

            // Get pixels of the WriteableBitmap object
            Stream pixelStream = finalImage.PixelBuffer.AsStream();

            byte[] pixels = new byte[pixelStream.Length];
            await pixelStream.ReadAsync(pixels, 0, pixels.Length);

            // Save the image file with png extension
            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)finalImage.PixelWidth, (uint)finalImage.PixelHeight, 96.0, 96.0, pixels);
            await encoder.FlushAsync();

            ShowFlyoutAboveInkToolbar?.Invoke("Image Saved");
        }
示例#7
0
        /// <summary>
        /// Resize the file to a certain level
        /// </summary>
        /// <param name="name">Final Name Of the Files Generated </param>
        /// <param name="hsize">Height Of Image</param>
        /// <param name="wsize">Width Of Image</param>
        /// <param name="file">The File That Needs To Be Resized</param>
        /// <param name="folder">Location of the final file</param>
        public async static Task Resizer(String name, uint hsize, uint wsize, StorageFile file, StorageFolder folder)
        {
            StorageFile newFile = await folder.CreateFileAsync(name);

            using (var sourceStream = await file.OpenAsync(FileAccessMode.Read))
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);

                BitmapTransform transform = new BitmapTransform()
                {
                    ScaledHeight = hsize, ScaledWidth = wsize
                };
                PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Rgba8,
                    BitmapAlphaMode.Straight,
                    transform,
                    ExifOrientationMode.RespectExifOrientation,
                    ColorManagementMode.DoNotColorManage);

                using (var destinationStream = await newFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destinationStream);

                    encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, wsize, hsize, 100, 100, pixelData.DetachPixelData());
                    await encoder.FlushAsync();
                }
            }
        }
示例#8
0
        private async Task <byte[]> ImageToBytes(IRandomAccessStream sourceStream)
        {
            byte[] imageArray;

            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);

            var transform = new BitmapTransform {
                ScaledWidth = decoder.PixelWidth, ScaledHeight = decoder.PixelHeight
            };
            PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                BitmapPixelFormat.Rgba8,
                BitmapAlphaMode.Straight,
                transform,
                ExifOrientationMode.RespectExifOrientation,
                ColorManagementMode.DoNotColorManage);

            using (var destinationStream = new InMemoryRandomAccessStream())
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destinationStream);

                encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, decoder.PixelWidth,
                                     decoder.PixelHeight, 96, 96, pixelData.DetachPixelData());
                await encoder.FlushAsync();

                BitmapDecoder outputDecoder = await BitmapDecoder.CreateAsync(destinationStream);

                await destinationStream.FlushAsync();

                imageArray = (await outputDecoder.GetPixelDataAsync()).DetachPixelData();
            }
            return(imageArray);
        }
示例#9
0
        public static async Task <StorageFile> WriteableBitmapToTemporaryFile(WriteableBitmap WB, string fileName)
        {
            Guid endcoderID             = GetBitmapEncoderId(fileName);
            DisplayInformation dispInfo = DisplayInformation.GetForCurrentView();
            StorageFile        file     = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

            using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(endcoderID, stream);

                Stream pixelStream = WB.PixelBuffer.AsStream();
                byte[] pixels      = new byte[pixelStream.Length];
                await pixelStream.ReadAsync(pixels, 0, pixels.Length);

                encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                     BitmapAlphaMode.Straight,
                                     (uint)WB.PixelWidth,
                                     (uint)WB.PixelHeight,
                                     dispInfo.LogicalDpi,
                                     dispInfo.LogicalDpi,
                                     pixels);

                await encoder.FlushAsync();
            }
            return(file);
        }
示例#10
0
        private async System.Threading.Tasks.Task <string> GenerateBarcodeImage(string detectedBarcode, StorageFile pictureFile)
        {
            var barcodeWriter = new BarcodeWriter();

            barcodeWriter.Format = detectedBarcode.Length == 8 ? ZXing.BarcodeFormat.EAN_8 : ZXing.BarcodeFormat.EAN_13;

            var result = barcodeWriter.Write(detectedBarcode);
            var path   = "";

            try
            {
                path = pictureFile.Path;
                using (IRandomAccessStream stream = await pictureFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

                    // Get pixels of the WriteableBitmap object
                    Stream pixelStream = result.PixelBuffer.AsStream();
                    byte[] pixels      = new byte[pixelStream.Length];
                    await pixelStream.ReadAsync(pixels, 0, pixels.Length);

                    // Save the image file with jpg extension
                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)result.PixelWidth, (uint)result.PixelHeight, 96.0, 96.0, pixels);
                    await encoder.FlushAsync();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return(path);
        }
示例#11
0
        public async Task <Stream> Encode()
        {
            try
            {
                Stopwatch stopwatchEncode = new Stopwatch();
                stopwatchEncode.Start();
                IRandomAccessStream imageStream   = (IRandomAccessStream) new InMemoryRandomAccessStream();
                BitmapEncoder       bitmapEncoder = await GraffitiEncoder.BuildEncoder(imageStream);

                BitmapPixelFormat pixelFormat;
                byte[]            imageBinaryData1 = GraffitiEncoder.GetImageBinaryData1(this._bitmap, out pixelFormat);
                int    num1        = (int)pixelFormat;
                int    num2        = 0;
                int    pixelWidth  = ((BitmapSource)this._bitmap).PixelWidth;
                int    pixelHeight = ((BitmapSource)this._bitmap).PixelHeight;
                double dpiX        = 72.0;
                double dpiY        = 72.0;
                byte[] pixels      = imageBinaryData1;
                bitmapEncoder.SetPixelData((BitmapPixelFormat)num1, (BitmapAlphaMode)num2, (uint)pixelWidth, (uint)pixelHeight, dpiX, dpiY, pixels);
                await WindowsRuntimeSystemExtensions.AsTask(bitmapEncoder.FlushAsync()).ConfigureAwait(false);

                long size = (long)imageStream.Size;
                stopwatchEncode.Stop();
                Execute.ExecuteOnUIThread((Action)(() => {}));
                return(WindowsRuntimeStreamExtensions.AsStreamForRead((IInputStream)imageStream));
            }
            catch
            {
                return(null);
            }
        }
示例#12
0
        async Task saveDebugImage(SoftwareBitmap bitmap, IList <PredictionModel> result)
        {
            WriteableBitmap newImage = new WriteableBitmap(bitmap.PixelWidth, bitmap.PixelHeight);

            bitmap.CopyToBuffer(newImage.PixelBuffer);
            for (int predictIdx = 0; predictIdx < result.Count; predictIdx++)
            {
                PredictionModel predictInfo = result[predictIdx];
                newImage.DrawRectangle((int)predictInfo.BoundingBox.Left * bitmap.PixelWidth,
                                       (int)predictInfo.BoundingBox.Top * bitmap.PixelHeight,
                                       (int)predictInfo.BoundingBox.Width * bitmap.PixelWidth,
                                       (int)predictInfo.BoundingBox.Height * bitmap.PixelHeight,
                                       Colors.Red);
            }

            Windows.Storage.StorageFile testFile = await folder.CreateFileAsync("test.jpg", Windows.Storage.CreationCollisionOption.ReplaceExisting);

            using (IRandomAccessStream stream = await testFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                Guid          BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
                BitmapEncoder encoder           = await BitmapEncoder.CreateAsync(BitmapEncoderGuid, stream);

                Stream pixelStream = newImage.PixelBuffer.AsStream();
                byte[] pixels      = new byte[pixelStream.Length];
                await pixelStream.ReadAsync(pixels, 0, pixels.Length);

                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                                     (uint)newImage.PixelWidth,
                                     (uint)newImage.PixelHeight,
                                     96.0,
                                     96.0,
                                     pixels);
                await encoder.FlushAsync();
            }
        }
        private async void TransferMgr_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            var         deferral = args.Request.GetDeferral();
            DataPackage package  = args.Request.Data;

            package.Properties.Title = "晒课表";

            scheduleBitpmap = new RenderTargetBitmap();
            await scheduleBitpmap.RenderAsync(scheduleGrid);

            var buffer = await scheduleBitpmap.GetPixelsAsync();

            InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
            BitmapEncoder encoder          = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ras);

            using (Stream stream = buffer.AsStream())
            {
                byte[] pixels = new byte[stream.Length];
                await stream.ReadAsync(pixels, 0, pixels.Length);

                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                                     (uint)scheduleBitpmap.PixelWidth,
                                     (uint)scheduleBitpmap.PixelHeight,
                                     96.0,
                                     96.0,
                                     pixels);
            }
            await encoder.FlushAsync();


            var streamRef = RandomAccessStreamReference.CreateFromStream(ras);

            package.SetBitmap(streamRef);
            deferral.Complete();
        }
示例#14
0
        private async void Encode(byte[] data, uint w, uint h, InMemoryRandomAccessStream stream)
        {
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

            encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, w, h, 96.0, 96.0, data);
            await encoder.FlushAsync();
        }
示例#15
0
        private async Task <StorageFile> WriteableBitmapToStorageFile(WriteableBitmap WB)
        {
            string FileName          = Guid.NewGuid().ToString() + ".jpg";
            Guid   BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
            var    file = await Windows.Storage.KnownFolders.PicturesLibrary.CreateFileAsync(FileName, CreationCollisionOption.GenerateUniqueName);

            // var file = await Windows.Storage.ApplicationData.Current.TemporaryFolder.CreateFileAsync(FileName, CreationCollisionOption.GenerateUniqueName);
            using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoderGuid, stream);

                Stream pixelStream = WB.PixelBuffer.AsStream();
                byte[] pixels      = new byte[pixelStream.Length];
                await pixelStream.ReadAsync(pixels, 0, pixels.Length);

                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                                     (uint)WB.PixelWidth,
                                     (uint)WB.PixelHeight,
                                     96.0,
                                     96.0,
                                     pixels);
                await encoder.FlushAsync();
            }
            return(file);
        }
示例#16
0
        public async System.Threading.Tasks.Task saveImageAsync()
        {
            Stream pixelStream = this.bitmap1.PixelBuffer.AsStream();

            byte[] pixels = new byte[pixelStream.Length];
            await pixelStream.ReadAsync(pixels, 0, pixels.Length);

            var savePicker = new Windows.Storage.Pickers.FileSavePicker();

            savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;

            // dropdown menu of file types the user can save the file as
            savePicker.FileTypeChoices.Add("PNG", new List <string>()
            {
                ".png"
            });

            // default file name if the user does not type one in or select a file to replace
            savePicker.SuggestedFileName = "IR_Capture";

            Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite);

                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)bitmap1.PixelWidth, (uint)bitmap1.PixelHeight, 96.0, 96.0, pixels);
                await encoder.FlushAsync();
            }
        }
示例#17
0
        public async Task <byte[]> SaveToBytesAsync(ImageSource imageSource)
        {
            byte[] imageBuffer;
            var    localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            var    file        = await localFolder.CreateFileAsync("temp.jpg", CreationCollisionOption.ReplaceExisting);

            using (var ras = await file.OpenAsync(FileAccessMode.ReadWrite, StorageOpenOptions.None))
            {
                WriteableBitmap bitmap = imageSource as WriteableBitmap;
                var             stream = bitmap.PixelBuffer.AsStream();
                byte[]          buffer = new byte[stream.Length];
                await stream.ReadAsync(buffer, 0, buffer.Length);

                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ras);

                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96.0, 96.0, buffer);
                await encoder.FlushAsync();

                var imageStream = ras.AsStream();
                imageStream.Seek(0, SeekOrigin.Begin);
                imageBuffer = new byte[imageStream.Length];
                var re = await imageStream.ReadAsync(imageBuffer, 0, imageBuffer.Length);
            }
            await file.DeleteAsync(StorageDeleteOption.Default);

            return(imageBuffer);
        }
示例#18
0
        public async Task SaveQRCodeAsync(WriteableBitmap qRImageUrl)
        {
            FileSavePicker savePicker = new FileSavePicker();

            savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            savePicker.FileTypeChoices.Add("Image", new List <string>()
            {
                ".jpg", ".png"
            });
            savePicker.SuggestedFileName = "QRCode";

            StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);

                    Stream pixelStream = qRImageUrl.PixelBuffer.AsStream();
                    byte[] pixels      = new byte[pixelStream.Length];
                    await pixelStream.ReadAsync(pixels, 0, pixels.Length);

                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                                         (uint)qRImageUrl.PixelWidth,
                                         (uint)qRImageUrl.PixelHeight,
                                         150.0,
                                         150.0,
                                         pixels);
                    await encoder.FlushAsync();
                }
            }
        }
示例#19
0
        public static async Task <Uri> SaveWritableBitmapToTileImageCache(WriteableBitmap wb, string tag)
        {
            var folder = (await ApplicationData.Current.LocalFolder.TryGetItemAsync(tileImageCacheFolderName)) as StorageFolder;

            if (folder == null)
            {
                folder = await CreateTileCacheFolder();
            }

            var fileName = DateTime.Now.ToString("yyyyMMddHHmm") + "-" + Guid.NewGuid() + "-" + tag + ".jpg";
            var file     = await folder.CreateFileAsync(fileName);

            using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

                Stream pixelStream = wb.PixelBuffer.AsStream();
                byte[] pixels      = new byte[pixelStream.Length];
                await pixelStream.ReadAsync(pixels, 0, pixels.Length);

                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                                     (uint)wb.PixelWidth,
                                     (uint)wb.PixelHeight,
                                     96.0,
                                     96.0,
                                     pixels);
                await encoder.FlushAsync();
            }

            return(new Uri($"ms-appdata:///local/{tileImageCacheFolderName}/{fileName}"));
        }
示例#20
0
        private async void GoRun()
        {
            RenderTargetBitmap bmp = new RenderTargetBitmap();
            await bmp.RenderAsync(GridEmoji);

            IBuffer buffer = await bmp.GetPixelsAsync();

            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".png";

            StorageFolder savedPics = KnownFolders.SavedPictures;
            // 创建新文件
            StorageFile newFile = await savedPics.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

            // 获取文件流
            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)bmp.PixelWidth,
                                    (uint)bmp.PixelHeight,
                                    96d, 96d, data);
            await pngEncoder.FlushAsync();

            streamOut.Dispose();
        }
示例#21
0
        private async void Savetoimage_Clicked(object sender, RoutedEventArgs e)
        {
            var piclib = Windows.Storage.KnownFolders.PicturesLibrary;

            foreach (var item in MyPrintPages.Items)
            {
                var rect = item as Rectangle;
                RenderTargetBitmap renderbmp = new RenderTargetBitmap();
                await renderbmp.RenderAsync(rect);

                var pixels = await renderbmp.GetPixelsAsync();

                var file = await piclib.CreateFileAsync("webview.png", Windows.Storage.CreationCollisionOption.GenerateUniqueName);

                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

                    byte[] bytes = pixels.ToArray();
                    encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                         BitmapAlphaMode.Ignore,
                                         (uint)rect.Width, (uint)rect.Height,
                                         0, 0, bytes);
                    await encoder.FlushAsync();
                }
            }
        }
示例#22
0
        /// <summary>
        ///     Saves the contents of the given <see cref="UIElement"/> inside the given file.
        /// </summary>
        /// <param name="uiElement"> The element to store. </param>
        /// <param name="file"> The file where to store the image. </param>
        /// <returns> A task that enables this method to be awaited. </returns>
        private static async Task SaveUiElementAsImageFileAsync(UIElement uiElement, StorageFile file)
        {
            // Render the current view to the target bitmap. Reference from: https://stackoverflow.com/questions/41354024/uwp-save-grid-as-png
            RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
            await renderTargetBitmap.RenderAsync(uiElement);

            // Obtain the pixels from the rendered bitmap
            byte[] pixels = (await renderTargetBitmap.GetPixelsAsync()).ToArray();

            // Write the result as a PNG image.
            using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                BitmapEncoder bitmapEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);

                bitmapEncoder.SetPixelData(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Premultiplied,
                    (uint)renderTargetBitmap.PixelWidth,
                    (uint)renderTargetBitmap.PixelHeight,
                    DisplayInformation.GetForCurrentView().RawDpiX,
                    DisplayInformation.GetForCurrentView().RawDpiY,
                    pixels);

                await bitmapEncoder.FlushAsync();
            }
        }
示例#23
0
        private async Task <Uri> SaveImageAsync(WriteableBitmap writableBitmap, string key)
        {
            //var uri =  await _fileStorageService.CreateFileAsync(key, "png");

            var storageFile = (StorageFile)await _fileStorageService.GetFileObjectAsync(key);

            IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.ReadWrite);

            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId,
                                                                    stream);

            // Get pixels of the WriteableBitmap object
            Stream pixelStream = writableBitmap.PixelBuffer.AsStream();

            byte[] pixels = new byte[pixelStream.Length];
            await pixelStream.ReadAsync(pixels, 0, pixels.Length);

            encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                 BitmapAlphaMode.Straight,
                                 (uint)writableBitmap.PixelWidth,
                                 (uint)writableBitmap.PixelHeight,
                                 96.0,
                                 96.0,
                                 pixels);
            await encoder.FlushAsync();

            stream.Dispose();
            pixelStream.Dispose();

            return(_fileStorageService.GetUriFromFile(storageFile));
        }
示例#24
0
        private async Task ResizeImage(StorageFile sourceFile, StorageFile destinationFile)
        {
            using (var sourceStream = await sourceFile.OpenAsync(FileAccessMode.Read))
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);

                var newWidth  = Math.Min(800, decoder.PixelWidth);
                var newHeight = newWidth * decoder.PixelHeight / decoder.PixelWidth;

                BitmapTransform transform = new BitmapTransform()
                {
                    ScaledHeight = newHeight, ScaledWidth = newWidth
                };
                PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Rgba8,
                    BitmapAlphaMode.Straight,
                    transform,
                    ExifOrientationMode.RespectExifOrientation,
                    ColorManagementMode.DoNotColorManage);

                using (var destinationStream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder =
                        await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destinationStream);

                    encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, newWidth, newHeight, 96,
                                         96, pixelData.DetachPixelData());
                    await encoder.FlushAsync();
                }
            }
        }
示例#25
0
        protected async Task <string> SaveBitmapFile(WriteableBitmap wb)
        {
            EventSource.Log.Debug("SaveBitmapFile()");

            // Copy our current color image
            DateTime now      = DateTime.Now;
            string   fileName = "KinectPhotobooth" + "-" + now.ToString("s").Replace(":", "-") + "-" + now.Millisecond.ToString() + ".png";

            StorageFile file = await this.targetFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);

            IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite);

            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

            Stream pixelStream = wb.PixelBuffer.AsStream();

            byte[] pixels = new byte[pixelStream.Length];
            await pixelStream.ReadAsync(pixels, 0, pixels.Length);

            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)wb.PixelWidth, (uint)wb.PixelHeight, 96.0, 96.0, pixels);

            // clean up
            pixelStream.Dispose();
            await encoder.FlushAsync();

            await stream.FlushAsync();

            stream.Dispose();

            return(fileName);
        }
        private async Task SaveStreamToFile(IRandomAccessStream imageStream, int width, int height, string fileName = null)
        {
            WriteableBitmap bitmap = new WriteableBitmap(width, height);

            bitmap.SetSource(imageStream);

            string name = string.IsNullOrEmpty(fileName) ? Guid.NewGuid().ToString() : fileName;

            var stFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(name + ".png", CreationCollisionOption.ReplaceExisting);

            using (IRandomAccessStream stream = await stFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

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

            Debug.WriteLine(stFile.Path);
        }
示例#27
0
        public async Task <BitmapImage> Displayimage(int[,] image)
        {
            byte[] pixelBytes = new byte[image.Length * 4];
            int    width      = image.GetLength(0);
            int    height     = image.GetLength(1);

            for (int i = 0; i < height; i++)
            {
                for (int j = 0; j < width; j++)
                {
                    int byteIndex = (i * width + j) * 4;

                    pixelBytes[byteIndex]     = (byte)image[j, i];
                    pixelBytes[byteIndex + 1] = (byte)image[j, i];
                    pixelBytes[byteIndex + 2] = (byte)image[j, i];
                    pixelBytes[byteIndex + 3] = 255;
                }
            }

            InMemoryRandomAccessStream inMemoryRandomAccessStream = new InMemoryRandomAccessStream();
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, inMemoryRandomAccessStream);

            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)width, (uint)height, 96.0, 96.0, pixelBytes);
            await encoder.FlushAsync();

            BitmapImage bitmapImage = new BitmapImage();

            bitmapImage.SetSource(inMemoryRandomAccessStream);
            return(bitmapImage);
        }
        /*public static IAsyncOperation<bool> RenderToPngAsync(this UIElement lt, string filename)
         * {
         *  return RenderToPngAsync(lt, filename).AsAsyncOperation();
         * } */

        public static async Task <bool> RenderToPngAsync(this UIElement lt, string filename)
        {
#if __UAP__
            var y = new RenderTargetBitmap();
            await y.RenderAsync(lt);

            Windows.Storage.Streams.IBuffer px = await y.GetPixelsAsync();

            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

            if (file != null)
            {
                CachedFileManager.DeferUpdates(file);
                using (Windows.Storage.Streams.IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

                    encoder.IsThumbnailGenerated = false;
                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)y.PixelWidth, (uint)y.PixelHeight, displayInfo.RawDpiX, displayInfo.RawDpiY, px.ToArray());
                    await encoder.FlushAsync();
                }
                await CachedFileManager.CompleteUpdatesAsync(file);

                return(true);
            }
#endif
            return(false);
        }
示例#29
0
        public static async Task <BitmapSource> CreateScaledBitmapFromStreamAsync(WebView web, IRandomAccessStream source)
        {
            int             height  = Convert.ToInt32(web.ActualHeight);
            int             width   = Convert.ToInt32(web.ActualWidth);
            WriteableBitmap bitmap  = new WriteableBitmap(width, height);
            BitmapDecoder   decoder = await BitmapDecoder.CreateAsync(source);

            BitmapTransform transform = new BitmapTransform();

            transform.ScaledHeight = (uint)height;
            transform.ScaledWidth  = (uint)width;
            PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                BitmapPixelFormat.Bgra8,
                BitmapAlphaMode.Straight,
                transform,
                ExifOrientationMode.RespectExifOrientation,
                ColorManagementMode.DoNotColorManage);

            pixelData.DetachPixelData().CopyTo(bitmap.PixelBuffer);
            var savefile = await ApplicationData.Current.LocalFolder.CreateFileAsync("inkSample", CreationCollisionOption.ReplaceExisting);

            using (IRandomAccessStream stream = await savefile.OpenAsync(FileAccessMode.ReadWrite))
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

                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();
            }
            return(bitmap);
        }
示例#30
0
        public static async Task savePngFile(WriteableBitmap bitmap, String filename)
        {
            StorageFolder local = Windows.Storage.ApplicationData.Current.LocalCacheFolder;
            StorageFile   sFile = await local.CreateFileAsync(filename, Windows.Storage.CreationCollisionOption.ReplaceExisting);

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