// If showPicker == false => PicturesLibrary capability must be set in client app public static async Task<IStorageFile> CreateBitmapFromElement(FrameworkElement uielement, bool showPicker = true, string filenamePrefix = "receipt") { try { var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(uielement); var file = await SaveFile(showPicker, filenamePrefix); var pixelBuffer = await renderTargetBitmap.GetPixelsAsync(); using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi; var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint) renderTargetBitmap.PixelWidth, (uint) renderTargetBitmap.PixelHeight, logicalDpi, logicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); } return file; } catch (Exception ex) { Debug.WriteLine(ex); return null; } }
public static async Task<IBuffer> SaveAsPngIntoBufferAsync(this Canvas canvas, double _scaleFactor, int dpiForImage = 200) { //string currentresolution = Window.Current.Bounds.Width * scaleFactor + "*" + Window.Current.Bounds.Height * scaleFactor; RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(canvas); var pixels = await renderTargetBitmap.GetPixelsAsync(); using (IRandomAccessStream stream = new InMemoryRandomAccessStream()) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); byte[] bytes = pixels.ToArray(); await CoreWindow.GetForCurrentThread().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)(canvas.ActualWidth * _scaleFactor), (uint)(canvas.ActualHeight * _scaleFactor), dpiForImage, dpiForImage, bytes); }); await encoder.FlushAsync(); stream.Seek(0); var buffer = WindowsRuntimeBuffer.Create((int)stream.Size); await stream.ReadAsync(buffer, (uint)stream.Size, InputStreamOptions.None); return buffer; } }
/// <summary> /// Start of the Drag and Drop operation: we set some content and change the DragUI /// depending on the selected options /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private async void SourceGrid_DragStarting(Windows.UI.Xaml.UIElement sender, Windows.UI.Xaml.DragStartingEventArgs args) { args.Data.SetText(SourceTextBox.Text); if ((bool)DataPackageRB.IsChecked) { // Standard icon will be used as the DragUIContent args.DragUI.SetContentFromDataPackage(); } else if ((bool)CustomContentRB.IsChecked) { // Generate a bitmap with only the TextBox // We need to take the deferral as the rendering won't be completed synchronously var deferral = args.GetDeferral(); var rtb = new RenderTargetBitmap(); await rtb.RenderAsync(SourceTextBox); var buffer = await rtb.GetPixelsAsync(); var bitmap = SoftwareBitmap.CreateCopyFromBuffer(buffer, BitmapPixelFormat.Bgra8, rtb.PixelWidth, rtb.PixelHeight, BitmapAlphaMode.Premultiplied); args.DragUI.SetContentFromSoftwareBitmap(bitmap); deferral.Complete(); } // else just show the dragged UIElement }
private async Task RenderUIElement(FrameworkElement elm, string fileName, int width, int height) { await System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(1)); using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream()) { var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(elm); var pixels = await renderTargetBitmap.GetPixelsAsync(); var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi; var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ms); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, logicalDpi, logicalDpi, pixels.ToArray()); await encoder.FlushAsync(); await X.Services.Image.Service.Instance.GenerateResizedImageAsync(width, elm.ActualWidth, elm.ActualHeight, ms, fileName + ".png", Services.Image.Service.location.TileFolder, height); } }
public static async Task<PixelColor[,]> GetPixels(RenderTargetBitmap source) { int width = source.PixelWidth; int height = source.PixelHeight; var result = new PixelColor[width, height]; var buffer = await source.GetPixelsAsync(); var bytes = buffer.ToArray(); for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var k = (y * width + x) * 4; result[x, y] = new PixelColor { Blue = bytes[k], Green = bytes[k + 1], Red = bytes[k + 2] }; } } return result; }
public static async Task<IRandomAccessStream> RenderToRandomAccessStream(this UIElement element) { var rtb = new RenderTargetBitmap(); await rtb.RenderAsync(element); IBuffer pixelBuffer = await rtb.GetPixelsAsync(); byte[] pixels = pixelBuffer.ToArray(); // Useful for rendering in the correct DPI DisplayInformation displayInformation = DisplayInformation.GetForCurrentView(); var stream = new InMemoryRandomAccessStream(); BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)rtb.PixelWidth, (uint)rtb.PixelHeight, displayInformation.RawDpiX, displayInformation.RawDpiY, pixels); await encoder.FlushAsync(); stream.Seek(0); return stream; }
//Creates RenderTargetBitmap from UI Element async Task<RenderTargetBitmap> CaptureToStreamAsync(FrameworkElement uielement, IRandomAccessStream stream, Guid encoderId) { try { var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(uielement); var pixels = await renderTargetBitmap.GetPixelsAsync(); var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi; var encoder = await BitmapEncoder.CreateAsync(encoderId, stream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, logicalDpi, logicalDpi, /*pixels.ToArray()*/ null); await encoder.FlushAsync(); return renderTargetBitmap; } catch { } return null; }
public async Task<string> RenderToBase64(UIElement element) { RenderTargetBitmap rtb = new RenderTargetBitmap(); await rtb.RenderAsync(element); var pixelBuffer = await rtb.GetPixelsAsync(); var pixels = pixelBuffer.ToArray(); // Useful for rendering in the correct DPI var displayInformation = DisplayInformation.GetForCurrentView(); var stream = new InMemoryRandomAccessStream(); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)rtb.PixelWidth, (uint)rtb.PixelHeight, displayInformation.RawDpiX, displayInformation.RawDpiY, pixels); await encoder.FlushAsync(); stream.Seek(0); // read bytes var bytes = new byte[stream.Size]; await stream.AsStream().ReadAsync(bytes, 0, bytes.Length); // create base64 return Convert.ToBase64String(bytes); }
async void SaveTheForest() { var displayInformation = DisplayInformation.GetForCurrentView(); var imageSize = new Size(ACTWIDTH, ACTHEIGHT); canvasOfAvaga.Measure(imageSize); canvasOfAvaga.UpdateLayout(); canvasOfAvaga.Arrange(new Rect(0, 0, imageSize.Width, imageSize.Height)); var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(canvasOfAvaga, Convert.ToInt32(imageSize.Width), Convert.ToInt32(imageSize.Height)); //await renderTargetBitmap.RenderAsync(canvasOfAvaga, Convert.ToInt32(ACTWIDTH), Convert.ToInt32(ACTHEIGHT)); var pixelBuffer = await renderTargetBitmap.GetPixelsAsync(); var picker = new FileSavePicker(); picker.FileTypeChoices.Add(".jpg",new[] {".jpg"}); var file = picker.PickSaveFileAsync(); //var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("D:\\Screen.jpg", CreationCollisionOption.ReplaceExisting); using (var fileStream = await (await picker.PickSaveFileAsync()).OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, fileStream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, displayInformation.LogicalDpi, displayInformation.LogicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); } }
public static async Task <StorageFile> AsUIScreenShotFileAsync(this UIElement elememtName, string ReplaceLocalFileNameWithExtension) { StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(ReplaceLocalFileNameWithExtension, CreationCollisionOption.ReplaceExisting); try { RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(); InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream(); // Render to an image at the current system scale and retrieve pixel contents await renderTargetBitmap.RenderAsync(elememtName); var pixelBuffer = await renderTargetBitmap.GetPixelsAsync(); // Encode image to an in-memory stream var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); //CreatingFolder // var folder = Windows.Storage.ApplicationData.Current.LocalFolder; RandomAccessStreamReference rasr = RandomAccessStreamReference.CreateFromStream(stream); var streamWithContent = await rasr.OpenReadAsync(); byte[] buffer = new byte[streamWithContent.Size]; await streamWithContent.ReadAsync(buffer.AsBuffer(), (uint)streamWithContent.Size, InputStreamOptions.None); using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite)) { using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0)) { using (DataWriter dataWriter = new DataWriter(outputStream)) { dataWriter.WriteBytes(buffer); await dataWriter.StoreAsync(); // dataWriter.DetachStream(); } // write data on the empty file: await outputStream.FlushAsync(); } await fileStream.FlushAsync(); } // await file.CopyAsync(folder, "tempFile.jpg", NameCollisionOption.ReplaceExisting); } catch (Exception ex) { Reporting.DisplayMessageDebugExemption(ex); } return(file); }
public static async Task RenderHelper(WriteableBitmap targetBitmap, FrameworkElement control, int x, int y) { RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(); const int PixelSize = 4; Frame topFrame; Page topPage; Panel topPanel; if (((topFrame = Window.Current.Content as Frame).Content != null) && ((topPage = topFrame.Content as Page) != null) && ((topPanel = topPage.Content as Panel) != null)) { /// Create a temporary container for the control to be rendered var tmpPanel = new StackPanel() { // We will try to render the control offscreen to avoid flickering RenderTransform = new TranslateTransform() { X = 1000, Y = 1000 } }; var oldParent = control.Parent; try { tmpPanel.Children.Add(control); topPanel.Children.Add(tmpPanel); await renderTargetBitmap.RenderAsync(control); } finally { tmpPanel.Children.Remove(control); topPanel.Children.Remove(tmpPanel); } var array = (await renderTargetBitmap.GetPixelsAsync()).ToArray(); using (var targetStream = targetBitmap.PixelBuffer.AsStream()) { var startOfLine = y * targetBitmap.PixelWidth * PixelSize; for (int i = 0; i < renderTargetBitmap.PixelHeight && i < targetBitmap.PixelHeight && startOfLine < targetBitmap.PixelBuffer.Capacity; i++) { targetStream.Seek(startOfLine + (PixelSize * x), SeekOrigin.Begin); startOfLine = startOfLine + targetBitmap.PixelWidth * PixelSize; if (i * renderTargetBitmap.PixelWidth * PixelSize < targetBitmap.PixelBuffer.Capacity) { await targetStream.WriteAsync(array, i * renderTargetBitmap.PixelWidth * PixelSize, (int)Math.Min(Math.Min(renderTargetBitmap.PixelWidth, targetBitmap.PixelWidth - x) * PixelSize, (long)targetBitmap.PixelBuffer.Capacity)); } else { break; } } } } }
private async void addPic(object sender, RoutedEventArgs e) { isAddPic = true; //打开资源管理器 FileOpenPicker filePicker = new FileOpenPicker(); filePicker.ViewMode = PickerViewMode.Thumbnail; filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; //可以添加的图片了诶性 filePicker.FileTypeFilter.Add(".jpg"); filePicker.FileTypeFilter.Add(".png"); filePicker.FileTypeFilter.Add(".bmp"); filePicker.FileTypeFilter.Add(".gif"); Windows.Storage.StorageFile file = await filePicker.PickSingleFileAsync(); //判断用户是否添加了图片 if (file != null) { //新建Token保存图片,以方便挂起状态恢复 ApplicationData.Current.LocalSettings.Values["MyToken"] = StorageApplicationPermissions.FutureAccessList.Add(file); BitmapImage bitmap = new BitmapImage(); using (var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)) { bitmap.SetSource(stream); this.myImg.Source = bitmap; } //将图片复制到缓存的文件夹,以解决文件权限的问题 StorageFolder applicationFolder = ApplicationData.Current.LocalFolder; StorageFolder folder = await applicationFolder.CreateFolderAsync("pic", CreationCollisionOption.OpenIfExists); StorageFile saveFile = await folder.CreateFileAsync(file.Name, CreationCollisionOption.OpenIfExists); RenderTargetBitmap tempbitmap = new RenderTargetBitmap(); await tempbitmap.RenderAsync(myImg); var pixelBuffer = await tempbitmap.GetPixelsAsync(); using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)tempbitmap.PixelWidth, (uint)tempbitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, pixelBuffer.ToArray() ); await encoder.FlushAsync(); } //记录缓存文件夹的路径 defaultpath = folder.Path.ToString() + '/' + file.Name; } else//用户使用默认的图片 { defaultpath = "ms-appx:///Assets/newOne.jpg"; } }
async void OnSaveAsAppBarButtonClick(object sender, RoutedEventArgs args) { FileSavePicker picker = new FileSavePicker(); picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; // Get the encoder information Dictionary <string, Guid> imageTypes = new Dictionary <string, Guid>(); IReadOnlyList <BitmapCodecInformation> codecInfos = BitmapEncoder.GetEncoderInformationEnumerator(); foreach (BitmapCodecInformation codecInfo in codecInfos) { List <string> extensions = new List <string>(); foreach (string extension in codecInfo.FileExtensions) { extensions.Add(extension); } string filetype = codecInfo.FriendlyName.Split(' ')[0]; picker.FileTypeChoices.Add(filetype, extensions); foreach (string mimeType in codecInfo.MimeTypes) { imageTypes.Add(mimeType, codecInfo.CodecId); } } // Get a selected StorageFile StorageFile storageFile = await picker.PickSaveFileAsync(); if (storageFile == null) { return; } // Open the StorageFile using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite)) { // Create an encoder Guid codecId = imageTypes[storageFile.ContentType]; BitmapEncoder encoder = await BitmapEncoder.CreateAsync(codecId, fileStream); // WritableBitmap を RenderTargetBitmapに書き換え var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(image); IBuffer pixelBuffer = await renderTargetBitmap.GetPixelsAsync(); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, 96, 96, pixelBuffer.ToArray()); await encoder.FlushAsync(); } }
async void SaveSnapshot(string fileName) { bool saved = this.paused; this.paused = true; this.StartStopCharts(); Exception error = null; try { #if DEBUG FrameworkElement element = RootLayout; #else FrameworkElement element = ContentPanel; #endif RenderTargetBitmap bitmap = new RenderTargetBitmap(); await bitmap.RenderAsync(element); IBuffer pixelBuffer = await bitmap.GetPixelsAsync(); byte[] pixels = pixelBuffer.ToArray(); var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; // Dropdown of file types the user can save the file as savePicker.FileTypeChoices.Add("PNG Images", new List <string>() { ".png" }); savePicker.SuggestedFileName = AppResources.DefaultSnapshotFileName; StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { using (var fileStream = await file.OpenStreamForWriteAsync()) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, fileStream.AsRandomAccessStream()); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96, 96, pixels); await encoder.FlushAsync(); } } } catch (Exception ex) { error = ex; } this.paused = saved; if (error != null) { await ShowError(error.Message, AppResources.ErrorSavingSnapshotCaption); } this.StartStopCharts(); }
private async void ImportButton_Click(object sender, RoutedEventArgs e) { if (_canvas == null) { return; } //###################################################### // These measurements are coming out all over the place. // Needs a more-or-less complete re-working. The wet ink // is functioning much better -- try using that? //###################################################### // scale target based on canvas zoom var zoom = _canvas.CurrentZoom(); int expectedWidth = (int)(ActualWidth * zoom); int expectedHeight = (int)(ActualHeight * zoom); // render to image var rtb = new RenderTargetBitmap(); await rtb.RenderAsync(ImageToImport, expectedWidth, expectedHeight).NotNull(); // Render control to RenderTargetBitmap // DPI mismatch -- use first attempt to calculate the real scale and render again. var scaleW = expectedWidth / (float)rtb.PixelWidth; var scaleH = expectedHeight / (float)rtb.PixelHeight; // render to image rtb = new RenderTargetBitmap(); await rtb.RenderAsync(ImageToImport, (int)(expectedWidth * scaleW), (int)(expectedHeight * scaleH)).NotNull(); // Render control to RenderTargetBitmap // get pixels from RTB var pixelBuffer = await rtb.GetPixelsAsync().NotNull(); // BGRA 8888 format var rawImage = new RawImageInterleaved_UInt8 { Data = pixelBuffer.ToArray(), Height = rtb.PixelHeight, Width = rtb.PixelWidth }; // render to canvas int left = (int)(Margin.Left); int top = (int)(Margin.Top); int right = left + (int)Width; int bottom = top + (int)Height; _canvas.ImportBytesScaled(rawImage, left, top, right, bottom); // ReSharper disable RedundantAssignment pixelBuffer = null; rtb = null; GC.Collect(); // ReSharper restore RedundantAssignment // make ourself invisible Visibility = Visibility.Collapsed; }
public static async Task <CompositionBrush> GetAlphaMaskAsync(this UIElement element) { CompositionBrush mask = null; try { //For some reason, using TextBlock and getting the AlphaMask //generates a shadow with a size more smaller than the control size. if (element is TextBlock textElement) { mask = textElement.GetAlphaMask(); } // We also use this option with images and shapes, even though have the option to // get the AlphaMask directly (in case it is clipped). else if (element is FrameworkElement frameworkElement) { var height = (int)frameworkElement.ActualHeight; var width = (int)frameworkElement.ActualWidth; if (height > 0 && width > 0) { var visual = ElementCompositionPreview.GetElementVisual(element); var elementVisual = visual.Compositor.CreateSpriteVisual(); elementVisual.Size = element.RenderSize.ToVector2(); var bitmap = new RenderTargetBitmap(); await bitmap.RenderAsync( element, width, height); var pixels = await bitmap.GetPixelsAsync(); using (var softwareBitmap = SoftwareBitmap.CreateCopyFromBuffer( pixels, BitmapPixelFormat.Bgra8, bitmap.PixelWidth, bitmap.PixelHeight, BitmapAlphaMode.Premultiplied)) { var brush = CompositionImageBrush.FromBGRASoftwareBitmap( visual.Compositor, softwareBitmap, new Size(bitmap.PixelWidth, bitmap.PixelHeight)); mask = brush.Brush; } } } } catch (Exception exc) { Debug.WriteLine($"Failed to get AlphaMask {exc}"); mask = null; } return(mask); }
public async Task <Tuple <byte[], int, int, double, double> > GetUIElementBitmapPixels(UIElement element, double offsetX, double offsetY) { RenderTargetBitmap bitmap = new RenderTargetBitmap(); await bitmap.RenderAsync(element); var pixels = await bitmap.GetPixelsAsync(); return(Tuple.Create(pixels.ToArray(), bitmap.PixelWidth, bitmap.PixelHeight, offsetX, offsetY)); }
private async Task <WriteableBitmap> SaveRecognitionCanvas1(Canvas canvas, double width, double height) { //Create a temporary image file for the recognition canvas - recogCanvas.png StorageFolder pictureFolder = ApplicationData.Current.LocalFolder; var savefile = await pictureFolder.CreateFileAsync("recogCanvas.png", CreationCollisionOption.GenerateUniqueName); if (savefile == null) { return(null); } IRandomAccessStream stream = await savefile.OpenAsync(FileAccessMode.ReadWrite); //Retrieve the pixel data from the canvas RenderTargetBitmap renderBitmap = new RenderTargetBitmap(); await renderBitmap.RenderAsync(canvas, (int)width, (int)height); IBuffer x = await renderBitmap.GetPixelsAsync(); //Set the IsTooLarge flag if the IBuffer is too long for writing. This prevents an exception and writes only half the image. //7664640 - max buffer size int value; if ((int)x.Length > 7664640) { //Write only the max length of data IsTooLarge = true; value = 7664640; } else { //Write the whole lenght of data value = (int)x.Length; } //Write the image pixels to a bitmap WriteableBitmap WBitmap = new WriteableBitmap((int)width, (int)height); using (Stream pb = WBitmap.PixelBuffer.AsStream()) { //This method will throw and exception if he pixel array is too large await pb.WriteAsync(WindowsRuntimeBufferExtensions.ToArray(x), 0, value); } Stream pixelStream = WBitmap.PixelBuffer.AsStream(); byte[] pixels = new byte[pixelStream.Length]; var length = pixels.Length; await pixelStream.ReadAsync(pixels, 0, pixels.Length); // Save the image file with png extension so the image is transparent for merging BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)WBitmap.PixelWidth, (uint)WBitmap.PixelHeight, 96.0, 96.0, pixels); await encoder.FlushAsync(); return(WBitmap); }
/// <summary> /// Draws the visuals of a <see cref="FrameworkElement"/> to a <see cref="BitmapImage"/> /// </summary> /// <param name="element">The <see cref="FrameworkElement"/> whose visuals are drawn to an image</param> /// <returns>An image representation of the <see cref="FrameworkElement"/></returns> public static async Task <BitmapImage> AsBitmapImage(this FrameworkElement element) { var bitmapImage = new BitmapImage(); #if WINDOWS_UWP var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(element, (int)element.Width, (int)element.Height); var pixels = await renderTargetBitmap.GetPixelsAsync(); using (var stream = new MemoryStream().AsRandomAccessStream()) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); byte[] bytes = pixels.ToArray(); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)element.Width, (uint)element.Height, 96, 96, bytes); stream.Seek(0); await bitmapImage.SetSourceAsync(stream); await encoder.FlushAsync(); } #else await Task.FromResult(0); // HACK var source = PresentationSource.FromVisual(element); var sourceBrush = new VisualBrush(element); var renderTargetBitmap = new RenderTargetBitmap((int)element.RenderSize.Width, (int)element.RenderSize.Height, 96, 96, PixelFormats.Pbgra32); var drawingVisual = new DrawingVisual(); var drawingContext = drawingVisual.RenderOpen(); using (drawingContext) { drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(element.RenderSize.Width, element.RenderSize.Height))); } renderTargetBitmap.Render(drawingVisual); var bitmapEncoder = new PngBitmapEncoder(); bitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap)); using (var stream = new MemoryStream()) { bitmapEncoder.Save(stream); stream.Seek(0, SeekOrigin.Begin); bitmapImage.BeginInit(); bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.StreamSource = stream; bitmapImage.EndInit(); } #endif return(bitmapImage); }
private async void WebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args) { try { if (webView.Source.ToString().Contains("pasfoto")) { RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(webView); var file = await KnownFolders.PicturesLibrary.CreateFileAsync("profilepicture.png", CreationCollisionOption.ReplaceExisting); if (file != null) { var pixelBuffer = await renderTargetBitmap.GetPixelsAsync(); using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, 96d, 96d, pixelBuffer.ToArray()); await encoder.FlushAsync(); } var filestream = await file.OpenAsync(FileAccessMode.Read); BitmapImage imageBit = new BitmapImage(); ImageBrush brush = new ImageBrush(); brush.Stretch = Stretch.UniformToFill; await imageBit.SetSourceAsync(filestream); brush.ImageSource = imageBit; Els.Fill = brush; } } else { await webView.InvokeScriptAsync("eval", new string[] { "document.getElementsByName('usernameFieldPanel:usernameFieldPanel_body:usernameField')[0].value='" + username + "';" }); await webView.InvokeScriptAsync("eval", new string[] { "document.getElementsByName('passwordFieldPanel:passwordFieldPanel_body:passwordField')[0].value='" + password + "';" }); await webView.InvokeScriptAsync("eval", new string[] { "document.getElementsByTagName('a')[0].click();" }); webView.Navigate(new Uri("https://merewa-elo.somtoday.nl/pasfoto/pasfoto_leerling.jpg?id=" + id)); } } catch (Exception e1) { Debug.WriteLine(e1.Message); } }
private static async Task RenderElementAsync(FrameworkElement element, IRandomAccessStream stream, Guid encoderId, Size size) { var bitmap = new RenderTargetBitmap(); await bitmap.RenderAsync(element, (int)size.Width, (int)size.Height); var pixels = await bitmap.GetPixelsAsync(); var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi; var encoder = await BitmapEncoder.CreateAsync(encoderId, stream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, logicalDpi, logicalDpi, pixels.ToArray()); await encoder.FlushAsync(); }
/// <summary> /// Encodes a WriteableBitmap object into a PNG stream. /// </summary> /// <param name="renderTargetBitmap">The render target bitmap.</param> /// <param name="outputStream">The image data stream.</param> /// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns> public static async Task SavePngAsync(this RenderTargetBitmap renderTargetBitmap, Stream outputStream) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, outputStream.AsRandomAccessStream()); var pixels = (await renderTargetBitmap.GetPixelsAsync()).ToArray(); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, ResolutionDpi, ResolutionDpi, pixels); await encoder.FlushAsync(); }
private async Task UpdateAppScreenshot() { var renderTarget = new RenderTargetBitmap(); await renderTarget.RenderAsync(Window.Current.Content); var pixels = await renderTarget.GetPixelsAsync(); _appScreenshot = CanvasBitmap.CreateFromBytes(_device, pixels, renderTarget.PixelWidth, renderTarget.PixelHeight, DirectXPixelFormat.B8G8R8A8UIntNormalized); }
/// <summary> /// Applys a blur to a UI element /// </summary> /// <param name="sourceElement">UIElement to blur, generally an Image control, but can be anything</param> /// <param name="blurAmount">Level of blur to apply</param> /// <returns>Blurred UIElement as BitmapImage</returns> public static async Task<BitmapImage> BlurElementAsync(this UIElement sourceElement, float blurAmount = 2.0f) { if (sourceElement == null) return null; var rtb = new RenderTargetBitmap(); await rtb.RenderAsync(sourceElement); var buffer = await rtb.GetPixelsAsync(); var array = buffer.ToArray(); var displayInformation = DisplayInformation.GetForCurrentView(); using (var stream = new InMemoryRandomAccessStream()) { var pngEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); pngEncoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint) rtb.PixelWidth, (uint) rtb.PixelHeight, displayInformation.RawDpiX, displayInformation.RawDpiY, array); await pngEncoder.FlushAsync(); stream.Seek(0); var canvasDevice = new CanvasDevice(); var bitmap = await CanvasBitmap.LoadAsync(canvasDevice, stream); var renderer = new CanvasRenderTarget(canvasDevice, bitmap.SizeInPixels.Width, bitmap.SizeInPixels.Height, bitmap.Dpi); using (var ds = renderer.CreateDrawingSession()) { var blur = new GaussianBlurEffect { BlurAmount = blurAmount, Source = bitmap }; ds.DrawImage(blur); } stream.Seek(0); await renderer.SaveAsync(stream, CanvasBitmapFileFormat.Png); var image = new BitmapImage(); await image.SetSourceAsync(stream); return image; } }
private async Task <bool> PromoteResultForSending(UIElement element, string emailAddress) { try { RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(element); //progress cameraContainer.Visibility = Visibility.Collapsed; progressRing.Visibility = Visibility.Visible; progressRing.IsActive = true; // var pixelBuffer = await renderTargetBitmap.GetPixelsAsync(); StorageFile imgFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("result.png", CreationCollisionOption.ReplaceExisting); // Encode the image to the selected file on disk using (var fileStream = await imgFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); } await new E().SendEmail(new Areas.EmailMessage { ToEmail = emailAddress, To = emailAddress, Subject = "Your Emotionizer Result!", Body = "Hi,\nThanks for taking the time and trying Emotionizer game at Microsoft Arabia office. Emotionizer game is built using Cognitive Services, an API - based service that allow you to bring the power of AI and Machine Learning into your App. Learn more here: https://www.microsoft.com/cognitive-services.\n\n Attached you will find your result.\nRegards,", From = "Microsoft", FromEmail = "*****@*****.**", Attachments = new ReadOnlyCollection <StorageFile>(new List <StorageFile> { { imgFile } }) }); return(true); } catch (Exception x) { Debug.WriteLine(x.Message); return(false); } }
private async Task <BitmapEncoder> CaptureView(FrameworkElement view, IRandomAccessStream stream) { int w = (int)view.ActualWidth; int h = (int)view.ActualHeight; if (w <= 0 || h <= 0) { throw new InvalidOperationException("Impossible to snapshot the view: view is invalid"); } RenderTargetBitmap targetBitmap = new RenderTargetBitmap(); await targetBitmap.RenderAsync(view, w, h); BitmapEncoder encoder; if (extension != "png") { var propertySet = new BitmapPropertySet(); var qualityValue = new BitmapTypedValue(quality, Windows.Foundation.PropertyType.Single); propertySet.Add("ImageQuality", qualityValue); encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream, propertySet); } else { encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); } var displayInformation = DisplayInformation.GetForCurrentView(); var pixelBuffer = await targetBitmap.GetPixelsAsync(); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)targetBitmap.PixelWidth, (uint)targetBitmap.PixelHeight, displayInformation.LogicalDpi, displayInformation.LogicalDpi, pixelBuffer.ToArray()); if (width != null && height != null && (width != w || height != h)) { encoder.BitmapTransform.ScaledWidth = (uint)width; encoder.BitmapTransform.ScaledWidth = (uint)height; } if (encoder == null) { throw new InvalidOperationException("Impossible to snapshot the view"); } await encoder.FlushAsync(); return(encoder); }
public async Task <SoftwareBitmap> CaptureElementToBitmap(UIElement uiElement) { RenderTargetBitmap renderTarget = new RenderTargetBitmap(); await renderTarget.RenderAsync(uiElement); IBuffer pixelBuffer = await renderTarget.GetPixelsAsync(); SoftwareBitmap bitmap = SoftwareBitmap.CreateCopyFromBuffer(pixelBuffer, BitmapPixelFormat.Bgra8, (int)uiElement.RenderSize.Width, (int)uiElement.RenderSize.Height, BitmapAlphaMode.Premultiplied); return(bitmap); }
private async Task<RenderTargetBitmap> CaptureToStreamAsync(FrameworkElement element, IRandomAccessStream stream, Guid encoderId) { var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(element); IBuffer pixels = await renderTargetBitmap.GetPixelsAsync(); double logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi; var encoder = await BitmapEncoder.CreateAsync(encoderId, stream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (UInt32)(renderTargetBitmap.PixelWidth), (UInt32)(renderTargetBitmap.PixelHeight), logicalDpi, logicalDpi, pixels.ToArray()); await encoder.FlushAsync(); return renderTargetBitmap; }
private async void Storage_OnClick(object sender, RoutedEventArgs e) { if (!_upload) { View.Address = "没有选择图片"; return; } if (File?.FileType == ".gif") { View.File = File; } else { DateTime time = DateTime.Now; string name = _name + time.Year + time.Month + time.Day + time.Hour + time.Minute + time.Second; var bitmap = new RenderTargetBitmap(); StorageFile file = await Folder.CreateFileAsync(name + ".jpg", CreationCollisionOption.GenerateUniqueName); await bitmap.RenderAsync(Stamp); var buffer = await bitmap.GetPixelsAsync(); try { using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { var encod = await BitmapEncoder.CreateAsync( BitmapEncoder.JpegEncoderId, stream); encod.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, buffer.ToArray() ); await encod.FlushAsync(); } View.File = file; } catch (ArgumentException) { View.Address = "没有选择图片"; } } await View.Jcloud(); //File = null; _upload = false; }
static async Task<RenderTargetBitmap> CaptureToStreamAsync(FrameworkElement uielement, IRandomAccessStream stream, Guid encoderId) { var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(uielement); IBuffer pixels = await renderTargetBitmap.GetPixelsAsync(); double logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi; var encoder = await BitmapEncoder.CreateAsync(encoderId, stream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (UInt32)(renderTargetBitmap.PixelWidth), (UInt32)(renderTargetBitmap.PixelHeight), logicalDpi, logicalDpi, pixels.ToArray()); await encoder.FlushAsync(); return renderTargetBitmap; }
// TextBox의 컨텐츠를 파일로 저장하는 메소드이다. // FileSavePicker와 WriteTextAsync로 텍스트 파일로 저장할 수 있다. // 또한 TextBox의 컨텐츠를 이미지로 저장할 수도 있다. public async void SaveAsync(Image source, TextBox target) { try { FileSavePicker picker = new FileSavePicker { SuggestedStartLocation = PickerLocationId.DocumentsLibrary }; picker.FileTypeChoices.Add("Image File", new List <string>() { image_file_extension }); picker.FileTypeChoices.Add("Text File", new List <string>() { text_file_extension }); picker.DefaultFileExtension = text_file_extension; StorageFile file = await picker.PickSaveFileAsync(); switch (file.FileType) { case text_file_extension: await FileIO.WriteTextAsync(file, target.Text); break; case image_file_extension: using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); RenderTargetBitmap render = new RenderTargetBitmap(); await render.RenderAsync(target); IBuffer buffer = await render.GetPixelsAsync(); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)render.PixelWidth, (uint)render.PixelHeight, 96.0, 96.0, buffer.ToArray()); await encoder.FlushAsync(); buffer = null; encoder = null; } break; default: break; } } catch { } }
/// <summary> /// Returns a byte array representative of the image associated with the UIElement. /// </summary> /// <param name="source">The UIElement whose image is to be returned.</param> /// <returns>the hash stringThe byte array representing the image.</returns> private async static Task <byte[]> GetByteArray(UIElement source) { var height = (int)source.RenderSize.Height; var width = (int)source.RenderSize.Width; RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(source, width, height); var buffer = await renderTargetBitmap.GetPixelsAsync(); return(buffer.ToArray()); }
/// <summary> /// Processes the RenderTargetBitmap and outputs the result to the output WriteableBitmap. /// </summary> /// <param name="rtb">The RenderTargetBitmap that typically includes a screen grab of the portion of UI.</param> /// <param name="wb">The WriteableBitmap that the effect output is written to.</param> /// <param name="pw">The pixel width of both bitmaps.</param> /// <param name="ph">The pixel height of both bitmaps.</param> /// <returns>A task that completes when the processing is complete.</returns> public override async Task ProcessBitmap(RenderTargetBitmap rtb, WriteableBitmap wb, int pw, int ph) { //var sw = new Stopwatch(); //sw.Start(); var rtbBuffer = await rtb.GetPixelsAsync(); var rtbPixels = rtbBuffer.GetPixels(); var wbBuffer = wb.PixelBuffer; var wbPixels = wbBuffer.GetPixels(); // Blur int radius = 1; for (int x = 0; x < pw; x++) { for (int y = 0; y < ph; y++) { int x1min = Math.Max(0, x - radius); int x1max = Math.Min(x + radius, pw - 1); int y1min = Math.Max(0, y - radius); int y1max = Math.Min(y + radius, ph - 1); int count = (x1max - x1min + 1) * (y1max - y1min + 1) + 7; var sum = new int[4]; for (int x1 = x1min; x1 <= x1max; x1++) { for (int y1 = y1min; y1 <= y1max; y1++) { for (int i = 0; i < 4; i++) { sum[i] += (x == x1 && y == y1) ? rtbPixels.Bytes[4 * (y1 * pw + x1) + i] * 8 : rtbPixels.Bytes[4 * (y1 * pw + x1) + i]; } } } for (int i = 0; i < 4; i++) { wbPixels.Bytes[4 * (y * pw + x) + i] = (byte)(sum[i] / count); } } } wbPixels.UpdateFromBytes(); wb.Invalidate(); //sw.Stop(); //new MessageDialog(sw.ElapsedMilliseconds.ToString()).ShowAsync(); }
public async Task SaveResultImageAsync() { var rtb = new RenderTargetBitmap(); await rtb.RenderAsync(ResultControl); var pixelBuffer = await rtb.GetPixelsAsync(); var displayInformation = DisplayInformation.GetForCurrentView(); var file = await PicturesHelper.SaveResultBufferAsync(pixelBuffer, rtb.PixelWidth, rtb.PixelHeight, displayInformation.RawDpiX, displayInformation.RawDpiY); GameStateMachineVm.ResultImage = new BitmapImage(new Uri(file.Path)); }
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); Messenger.Default.Register <bool>(this, "FileSaving", (bln) => { if (bln) { text_saveStatus.Text = "ファイルを保存しています..."; } else { text_saveStatus.Text = "ファイルを保存完了しました"; } }); Messenger.Default.Register <string>(this, "ShareResult", (message) => { DataTransferManager manager = DataTransferManager.GetForCurrentView(); manager.DataRequested += async(s, ex) => { DataRequest request = ex.Request; request.Data.Properties.Title = "学習結果"; request.Data.Properties.Description = "WordShuffleの学習結果を共有します"; request.Data.SetText(message); RenderTargetBitmap rtb = new RenderTargetBitmap(); await rtb.RenderAsync(stack_result); StorageFile tempFile = await KnownFolders.PicturesLibrary.CreateFileAsync("WordShuffleShareImage.jpg", CreationCollisionOption.ReplaceExisting); using (var stream = await tempFile.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); IBuffer pixelBuffer = await rtb.GetPixelsAsync(); byte[] pixels = pixelBuffer.ToArray(); float dpi = DisplayInformation.GetForCurrentView().LogicalDpi; encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)rtb.PixelWidth, (uint)rtb.PixelHeight, dpi, dpi, pixels); await encoder.FlushAsync(); request.Data.SetBitmap(RandomAccessStreamReference.CreateFromFile(tempFile)); } }; flyout_share.ShowAt(button_share); }); var vm = DataContext as MainViewModel; vm.SaveLearningResultCommand.Execute(null); }
public async Task Render(RenderTargetBitmap image) { var buffer = await image.GetPixelsAsync(); const int kMaxSPISize = 65000; /// 19200; int spilines = kMaxSPISize / (image.PixelWidth * 2); int spiblock = spilines * (image.PixelWidth * 2); var numPixels = image.PixelWidth * image.PixelHeight; var numPixelBytes = numPixels * 2; byte[] framebuffer = new byte[spiblock]; var y = 0; var offset = 0; for (int buff = 0; buff < numPixelBytes / spiblock; buff++) { offset = buff * spiblock * 2; byte[] pixels = WindowsRuntimeBufferExtensions.ToArray(buffer, (uint)offset, spiblock * 2); for (int frameBuff = 0, source = 0; frameBuff < framebuffer.Length; frameBuff += 2, source += 4) { int color565 = (((pixels[source + 0] & 0xF8) << 8) | ((pixels[source + 1] & 0xFC) << 3) | ((pixels[source + 2] & 0xF8) >> 3)); framebuffer[frameBuff] = (byte)((color565 >> 8) & 0xFF); framebuffer[frameBuff + 1] = (byte)((color565 & 0xFF)); } setWindow(0, y, image.PixelWidth, spilines); sendC(0x2C); sendD(framebuffer); y += spilines; } offset += spiblock * 2; var remainder = numPixelBytes % spiblock; if (remainder > 0) { byte[] framebuffer2 = new byte[remainder]; byte[] pixels = WindowsRuntimeBufferExtensions.ToArray(buffer, (uint)(offset), remainder * 2); for (int frameBuff = 0, source = 0; frameBuff < framebuffer2.Length; frameBuff += 2, source += 4) { int color565 = (((pixels[source + 0] & 0xF8) << 8) | ((pixels[source + 1] & 0xFC) << 3) | ((pixels[source + 2] & 0xF8) >> 3)); framebuffer2[frameBuff] = (byte)((color565 >> 8) & 0xFF); framebuffer2[frameBuff + 1] = (byte)((color565 & 0xFF)); } var linesLeft = image.PixelHeight - y; setWindow(0, y, image.PixelWidth, linesLeft); sendC(0x2C); sendD(framebuffer2); } }
private async void RenderImage(NotificationMessageAction <SoftwareBitmap> notificationMessageAction) { if (BaumCollection != null && BaumCollection.Count > 0) { if (BaumCollection.Where(x => x.IsMarked == true).Count() > 0) { SelectTree(BaumCollection.Where(x => x.IsMarked == true).First()); } //_selectedBaum = _BaumCollection.Where(x => x.IsMarked = true).First(); //RaisePropertyChanged(() => SelectedBaum); } RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(mapGrid); if (renderTargetBitmap.PixelHeight != 0 && renderTargetBitmap.PixelWidth != 0) { SoftwareBitmap softwareBitmap = new SoftwareBitmap(BitmapPixelFormat.Bgra8, renderTargetBitmap.PixelWidth, renderTargetBitmap.PixelHeight); softwareBitmap.DpiX = 600; softwareBitmap.DpiY = 600; softwareBitmap.CopyFromBuffer(await renderTargetBitmap.GetPixelsAsync()); notificationMessageAction.Execute(softwareBitmap); } //BitmapDecoder imagedecoder; //using (var imagestream = await Map.OpenAsync(FileAccessMode.Read)) //{ // imagedecoder = await BitmapDecoder.CreateAsync(imagestream); // CanvasDevice device = CanvasDevice.GetSharedDevice(); // CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, imagedecoder.PixelWidth, imagedecoder.PixelHeight, 96); // using (var ds = renderTarget.CreateDrawingSession()) // { // ds.Clear(Colors.White); // CanvasBitmap image = await CanvasBitmap.LoadAsync(device, imagestream); // ds.DrawImage(image); // //ds.DrawText(lblName.Text, new System.Numerics.Vector2(150, 150), Colors.Black); // } // await renderTarget.SaveAsync(imagestream, CanvasBitmapFileFormat.Jpeg); // BitmapImage bitmap = new BitmapImage(); // bitmap.SetSource(imagestream); // MapR = bitmap; //} }
private async void ImportButton_Click(object sender, RoutedEventArgs e) { if (_canvas == null || textBlockToRender == null) { return; } var margin = textBlockToRender.Margin.Top; // scale target based on canvas zoom var zoom = _canvas.CurrentZoom(); int expectedWidth = (int)(ActualWidth * zoom); int expectedHeight = (int)((ActualHeight - margin) * zoom); // render to image var rtb = new RenderTargetBitmap(); await rtb.RenderAsync(textBlockToRender, expectedWidth, expectedHeight).NotNull(); // Render control to RenderTargetBitmap // DPI mismatch -- use first attempt to calculate the real scale and render again. var scaleW = expectedWidth / (float)rtb.PixelWidth; var scaleH = expectedHeight / (float)rtb.PixelHeight; // render to image rtb = new RenderTargetBitmap(); await rtb.RenderAsync(textBlockToRender, (int)(expectedWidth * scaleW), (int)(expectedHeight * scaleH)).NotNull(); // Render control to RenderTargetBitmap // get pixels from RTB var pixelBuffer = await rtb.GetPixelsAsync().NotNull(); // BGRA 8888 format var rawImage = new RawImageInterleaved_UInt8 { Data = pixelBuffer.ToArray(), Height = rtb.PixelHeight, Width = rtb.PixelWidth }; // render to canvas int left = (int)(Margin.Left); int top = (int)(Margin.Top + textBlockToRender.Margin.Top); int right = left + (int)Width; int bottom = top + (int)(Height - margin); _canvas.ImportBytesScaled(rawImage, left, top, right, bottom); // ReSharper disable RedundantAssignment pixelBuffer = null; rtb = null; GC.Collect(); // ReSharper restore RedundantAssignment // make ourself invisible Visibility = Visibility.Collapsed; }
async public Task <int> preparePaintingAreaCanvasPixel() { RenderTargetBitmap retarbi = new RenderTargetBitmap(); Canvas canvas = PocketPaintApplication.GetInstance().PaintingAreaCanvas; await retarbi.RenderAsync(canvas); Windows.Storage.Streams.IBuffer buffer = await(retarbi.GetPixelsAsync()); pixelsCanvas = WindowsRuntimeBufferExtensions.ToArray(buffer); this.pixelHeightCanvas = retarbi.PixelHeight; this.pixelWidthCanvas = retarbi.PixelWidth; return(0); }
internal async Task UpdateAppScreenshotAsync() { var renderTarget = new RenderTargetBitmap(); var diaplayInfo = DisplayInformation.GetForCurrentView(); var scale = diaplayInfo.RawPixelsPerViewPixel; var scaleWidth = (int)Math.Ceiling(Window.Current.Bounds.Width / scale); var scaleHeight = (int)Math.Ceiling(Window.Current.Bounds.Height / scale); await renderTarget.RenderAsync(Window.Current.Content, scaleWidth, scaleHeight); var pixels = await renderTarget.GetPixelsAsync(); _appScreenshot = CanvasBitmap.CreateFromBytes(_device, pixels, renderTarget.PixelWidth, renderTarget.PixelHeight, DirectXPixelFormat.B8G8R8A8UIntNormalized); }
private async void getPixels(Point location) { var pixelBuffer = await _bitmap.GetPixelsAsync(); byte[] pixels = pixelBuffer.ToArray(); Color color = GetPixelColor(pixels, (int)(location.X * DisplayProperties.LogicalDpi / 96), (int)(location.Y * DisplayProperties.LogicalDpi / 96), (uint)_bitmap.PixelWidth, (uint)_bitmap.PixelHeight); SControl.setCurrentColor(color); _color = color; //SControl.Background = new SolidColorBrush(color); }
/// <summary> /// Event handler for the "Save Image.." button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void SaveImage_Click(object sender, RoutedEventArgs e) { if (RenderedGrid.Children.Count == 0) { rootPage.NotifyUser("You must add content before saving.", NotifyType.ErrorMessage); return; } // Render to an image at the current system scale and retrieve pixel contents RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(RenderedGrid); var pixelBuffer = await renderTargetBitmap.GetPixelsAsync(); var savePicker = new FileSavePicker(); savePicker.DefaultFileExtension = ".png"; savePicker.FileTypeChoices.Add(".png", new List <string> { ".png" }); savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; savePicker.SuggestedFileName = "snapshot.png"; // Prompt the user to select a file var saveFile = await savePicker.PickSaveFileAsync(); // Verify the user selected a file if (saveFile == null) { return; } // Encode the image to the selected file on disk using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); } rootPage.NotifyUser("File saved!", NotifyType.StatusMessage); }
/// <summary> /// Esegue il rendering di un FrameworkElement /// </summary> public async Task<WriteableBitmap> Screenshot(FrameworkElement ele) { // Render some UI to a RenderTargetBitmap var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(ele); // Get the pixel buffer and copy it into a WriteableBitmap var pixelBuffer = await renderTargetBitmap.GetPixelsAsync(); var width = renderTargetBitmap.PixelWidth; var height = renderTargetBitmap.PixelHeight; var wbmp = await new WriteableBitmap(1, 1).FromPixelBuffer(pixelBuffer, width, height); return wbmp; }
public async Task <byte[]> GetSnapshot() { if (Map == null) { return(null); } var rtb = new RenderTargetBitmap(); await rtb.RenderAsync(Map); var pixelBuffer = await rtb.GetPixelsAsync(); return(pixelBuffer.ToArray()); }
/// <summary> /// Processes the RenderTargetBitmap and outputs the result to the output WriteableBitmap. /// </summary> /// <param name="rtb">The RenderTargetBitmap that typically includes a screen grab of the portion of UI.</param> /// <param name="wb">The WriteableBitmap that the effect output is written to.</param> /// <param name="pw">The pixel width of both bitmaps.</param> /// <param name="ph">The pixel height of both bitmaps.</param> /// <returns>A task that completes when the processing is complete.</returns> public override async Task ProcessBitmapAsync(RenderTargetBitmap rtb, WriteableBitmap wb, int pw, int ph) { //var sw = new Stopwatch(); //sw.Start(); var rtbBuffer = await rtb.GetPixelsAsync(); var rtbPixels = rtbBuffer.GetPixels(); var wbBuffer = wb.PixelBuffer; var wbPixels = wbBuffer.GetPixels(); // Blur int radius = 1; for (int x = 0; x < pw; x++) for (int y = 0; y < ph; y++) { int x1min = Math.Max(0, x - radius); int x1max = Math.Min(x + radius, pw - 1); int y1min = Math.Max(0, y - radius); int y1max = Math.Min(y + radius, ph - 1); int count = (x1max - x1min + 1) * (y1max - y1min + 1) + 7; var sum = new int[4]; for (int x1 = x1min; x1 <= x1max; x1++) for (int y1 = y1min; y1 <= y1max; y1++) for (int i = 0; i < 4; i++) sum[i] += (x == x1 && y == y1) ? rtbPixels.Bytes[4 * (y1 * pw + x1) + i] * 8 : rtbPixels.Bytes[4 * (y1 * pw + x1) + i]; for (int i = 0; i < 4; i++) wbPixels.Bytes[4 * (y * pw + x) + i] = (byte)(sum[i] / count); } wbPixels.UpdateFromBytes(); wb.Invalidate(); //sw.Stop(); //new MessageDialog(sw.ElapsedMilliseconds.ToString()).ShowAsync(); }
public static async void templateCreator(Template t,Image I,Grid VisualTreeParent,int Hoffset, int Voffset,int ScaleFactor) { //say cheese VisualTreeParent.Children.Add(t); RenderTargetBitmap render = new RenderTargetBitmap(); await render.RenderAsync(t); var result = await render.GetPixelsAsync(); //print the photo WriteableBitmap source = new WriteableBitmap(ScaleFactor * render.PixelWidth, ScaleFactor * render.PixelHeight); using (Stream stream = source.PixelBuffer.AsStream()) { Byte[] res = new Byte[source.PixelHeight * source.PixelWidth * 4]; for (int i = 0; i < res.Length; i++) { res[i] = 0xff; } //عيب يا ابو عيسي :P Byte[] kareem = result.ToArray(); for (int i = 0, j = 0; i + 4 < source.PixelWidth * render.PixelHeight * 4 + Voffset * source.PixelWidth * 4; i = ((j / (render.PixelWidth * 4)) + Voffset) * source.PixelWidth * 4 + i % (render.PixelWidth * 4)) { if (kareem[j + 1] == 0 && kareem[j] == 0 && kareem[j + 2] == 0 && kareem[j + 3] == 255) { for (int l = 0; l < 3; l++) { res[i++ + Hoffset * 4] = kareem[j++]; } res[i++ + Hoffset * 4] = 0; j++; } else for (int l = 0; l < 4; l++) { res[i++ + Hoffset * 4] = 0xff; j++; } } await stream.WriteAsync(res, 0, res.Length); } VisualTreeParent.Children.Remove(t); I.Source = source; }
public async Task CaptureThumbnail(InMemoryRandomAccessStream ms) { var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(_renderElement); var pixels = await renderTargetBitmap.GetPixelsAsync(); var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi; var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ms); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, logicalDpi, logicalDpi, pixels.ToArray()); await encoder.FlushAsync(); }
public static async Task<string> CreateNormalTileImage(string cover, UIElement tile) { var fileName = MD5.GetMd5String(cover); var filePath = Path.Combine(LiveTilePicsDirectoryName, fileName); if (FileExists(filePath)) return filePath; if (cover.Contains("http")) { var target = new RenderTargetBitmap(); tile.Opacity = 1; await target.RenderAsync(tile); tile.Opacity = 0; var pixels = await target.GetPixelsAsync(); } else { } return filePath; }
private void OnShareBitmapData(DataProviderRequest request) { var deferral = request.GetDeferral(); Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { try { var file = await ApplicationData.Current.TemporaryFolder. CreateFileAsync("TempImage.png", CreationCollisionOption.ReplaceExisting); // Render XAML control to PNG image using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(SharedControl); var pixelBuffer = await renderTargetBitmap.GetPixelsAsync(); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, 96, 96, pixelBuffer.ToArray()); await encoder.FlushAsync(); } // Share file request.SetData(RandomAccessStreamReference.CreateFromFile(file)); } finally { deferral.Complete(); } }); }
private async void inicia_desenho_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(output); var pixelBuffer = await renderTargetBitmap.GetPixelsAsync(); var file = await KnownFolders.PicturesLibrary.CreateFileAsync("Teste.png", CreationCollisionOption.ReplaceExisting); using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, 96d, 96d, pixelBuffer.ToArray()); await encoder.FlushAsync(); } this.Frame.Navigate(typeof(PaginaDesenho)); }
/// <summary> /// Processes the RenderTargetBitmap and outputs the result to the output WriteableBitmap. /// </summary> /// <param name="rtb">The RenderTargetBitmap that typically includes a screen grab of the portion of UI.</param> /// <param name="wb">The WriteableBitmap that the effect output is written to.</param> /// <param name="pw">The pixel width of both bitmaps.</param> /// <param name="ph">The pixel height of both bitmaps.</param> /// <returns>A task that completes when the processing is complete.</returns> public override async Task ProcessBitmap(RenderTargetBitmap rtb, WriteableBitmap wb, int pw, int ph) { var rtbBuffer = await rtb.GetPixelsAsync(); var rtbPixels = rtbBuffer.GetPixels(); var wbBuffer = wb.PixelBuffer; var wbPixels = wbBuffer.GetPixels(); var r = this.Color.R; var g = this.Color.G; var b = this.Color.B; // Expand const int expansion = 1; for (int x = 0; x < pw; x++) for (int y = 0; y < ph; y++) { int x1min = Math.Max(0, x - expansion); int x1max = Math.Min(x + expansion, pw - 1); int y1min = Math.Max(0, y - expansion); int y1max = Math.Min(y + expansion, ph - 1); byte maxa = 0; for (int x1 = x1min; x1 <= x1max; x1++) for (int y1 = y1min; y1 <= y1max; y1++) { var a = rtbPixels.Bytes[4 * (y1 * pw + x1) + 3]; if (a > maxa) maxa = a; } wbPixels.Bytes[4 * (y * pw + x)] = b; wbPixels.Bytes[4 * (y * pw + x) + 1] = g; wbPixels.Bytes[4 * (y * pw + x) + 2] = r; wbPixels.Bytes[4 * (y * pw + x) + 3] = maxa; } wbPixels.UpdateFromBytes(); wb.Invalidate(); }
public async Task<RandomAccessStreamReference> GetDiagramAsync() { var bitmap = new RenderTargetBitmap(); await bitmap.RenderAsync(this.Content); var randomAccessStream = new InMemoryRandomAccessStream(); var pixels = await bitmap.GetPixelsAsync(); var displayInfo = DisplayInformation.GetForCurrentView(); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, randomAccessStream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, displayInfo.RawDpiX, displayInfo.RawDpiX, pixels.ToArray()); await encoder.FlushAsync(); return RandomAccessStreamReference.CreateFromStream(randomAccessStream); }
async Task SaveVisualElementToFile(FrameworkElement element, StorageFile file) { string fileName = "customphoto.jpg"; var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(element, 310, 150); var pixels = await renderTargetBitmap.GetPixelsAsync(); using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); byte[] bytes = pixels.ToArray(); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)element.Width * 2, (uint)element.Height * 2, 96, 96, bytes); await encoder.FlushAsync(); } }
private async void saveImgBtn_Click(object sender, RoutedEventArgs e) { // render canvas to bitmap var bitmap = new RenderTargetBitmap(); await bitmap.RenderAsync(canvas); // create file var savePicker = new FileSavePicker(); savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; savePicker.DefaultFileExtension = ".png"; savePicker.SuggestedFileName = "resizedImage"; savePicker.FileTypeChoices.Add("PNG", new string[] { ".png" }); var saveFile = await savePicker.PickSaveFileAsync(); //save bitmap to file using (var stream = await saveFile.OpenStreamForWriteAsync()) { var pixelBuffer = await bitmap.GetPixelsAsync(); var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi; var randomAccessStream = stream.AsRandomAccessStream(); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, randomAccessStream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, logicalDpi, logicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); } }
private async Task<WriteableBitmap> ClipPhotoHandleAsync(RenderTargetBitmap renderTargetBitmap) { IBuffer buffer = await renderTargetBitmap.GetPixelsAsync(); //创建程序文件存储 var appData = ApplicationData.Current.LocalFolder; IStorageFile saveFile = await appData.CreateFileAsync("QRCode.png", CreationCollisionOption.ReplaceExisting); //把图片存进去 using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, buffer.ToArray()); await encoder.FlushAsync(); } var writeableBmp = new WriteableBitmap(1, 1); using (var streamResult = await saveFile.OpenAsync(FileAccessMode.Read)) { writeableBmp.SetSource(streamResult); writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight); streamResult.Seek(0); writeableBmp.SetSource(streamResult); await saveFile.DeleteAsync(StorageDeleteOption.PermanentDelete); } return writeableBmp; }
public static async Task<string> ToBase64(RenderTargetBitmap bitmap) { var bytes = (await bitmap.GetPixelsAsync()).ToArray(); return await ToBase64(bytes, (uint) bitmap.PixelWidth, (uint) bitmap.PixelHeight); }
//lab 13 async private void Screenshot() { // Thread protetction on FileIO actions if (!isTakingScreenshot) { isTakingScreenshot = true; RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(RootGrid); var pixelBuffer = await renderTargetBitmap.GetPixelsAsync(); var savePicker = new FileSavePicker(); savePicker.DefaultFileExtension = ".png"; savePicker.FileTypeChoices.Add(".png", new List<string> { ".png" }); savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; savePicker.SuggestedFileName = "snapshot.png"; // Prompt the user to select a file var saveFile = await savePicker.PickSaveFileAsync(); // Verify the user selected a file if (saveFile != null) { // Encode the image to the selected file on disk using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); } } isTakingScreenshot = false; } }
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; //} }
public override object generatePeerImage() { int width = getWidth(); int height = getHeight(); if (width <= 0 || height <= 0) { width = getPreferredW(); height = getPreferredH(); } CodenameOneImage img = new CodenameOneImage(); img.@this(); img.name = "PeerImage: " + element.ToString(); IRandomAccessStream stream = new InMemoryRandomAccessStream(); CanvasBitmap cb = null; SilverlightImplementation.dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { if (element is WebView) { await ((WebView)element).CapturePreviewToStreamAsync(stream); await stream.FlushAsync(); stream.Seek(0); cb = await CanvasBitmap.LoadAsync(SilverlightImplementation.screen, stream); } else { RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(element); byte[] buf = renderTargetBitmap.GetPixelsAsync().AsTask().ConfigureAwait(false).GetAwaiter().GetResult().ToArray(); cb = CanvasBitmap.CreateFromBytes(SilverlightImplementation.screen, buf, width, height, SilverlightImplementation.pixelFormat, SilverlightImplementation.screen.Dpi); } img.image = new CanvasRenderTarget(SilverlightImplementation.screen, cb.SizeInPixels.Width, cb.SizeInPixels.Height, cb.Dpi); img.graphics.destination.drawImage(cb, 0, 0); img.graphics.destination.dispose(); }).AsTask().GetAwaiter().GetResult(); return ui.Image.createImage(img); }