public unsafe async static Task<WriteableBitmap> ToBitmapImageAsync(this BitmapHolder holder) { if (holder == null || holder.Pixels == null) return null; var writeableBitmap = new WriteableBitmap(holder.Width, holder.Height); using (var stream = writeableBitmap.PixelBuffer.AsStream()) { int length = holder.Pixels.Length; var buffer = new byte[length * 4]; fixed (int* srcPtr = holder.Pixels) { var b = 0; for (var i = 0; i < length; i++, b += 4) { var p = srcPtr[i]; buffer[b + 3] = (byte)((p >> 24) & 0xff); buffer[b + 2] = (byte)((p >> 16) & 0xff); buffer[b + 1] = (byte)((p >> 8) & 0xff); buffer[b + 0] = (byte)(p & 0xff); } stream.Write(buffer, 0, length * 4); } } writeableBitmap.Invalidate(); return writeableBitmap; }
private async void OnImageUrlChanged() { if (ImageUrl == null) { return; } var rass = RandomAccessStreamReference.CreateFromUri(new Uri(ImageUrl, UriKind.Absolute)); IRandomAccessStream stream = await rass.OpenReadAsync(); var decoder = await BitmapDecoder.CreateAsync(stream); Rect bounds = Window.Current.Bounds; //WriteableBitmap bmp = new WriteableBitmap((int)bounds.Width, (int)bounds.Height); var displayWidth = Math.Min(decoder.PixelWidth, bounds.Width); var displayHeight = Math.Min(decoder.PixelHeight, bounds.Height); WriteableBitmap bmp = new WriteableBitmap((int)displayWidth, (int)displayHeight); stream.Seek(0); //var blurFilter = new BlurFilter(60); using (var source = new RandomAccessStreamImageSource(stream)) using (var blurFilter = new LensBlurEffect(source, new LensBlurPredefinedKernel(LensBlurPredefinedKernelShape.Circle, 20))) //using (var filterEffect = new FilterEffect(source) { Filters = new[] { blurFilter } }) using (var renderer = new WriteableBitmapRenderer(blurFilter, bmp)) { bmp = await renderer.RenderAsync(); bmp.Invalidate(); BackgroundImage.Source = bmp; } }
async Task<WriteableBitmap> SelectImageFromPicker() { var picker = new FileOpenPicker(); picker.ViewMode = PickerViewMode.Thumbnail; picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".jpeg"); picker.FileTypeFilter.Add(".png"); StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { ImageProperties imgProp = await file.Properties.GetImagePropertiesAsync(); var savedPictureStream = await file.OpenAsync(FileAccessMode.Read); //set image properties and show the taken photo bitmap = new WriteableBitmap((int)imgProp.Width, (int)imgProp.Height); await bitmap.SetSourceAsync(savedPictureStream); bitmap.Invalidate(); SaveImageAsync(file); return bitmap; } else return null; }
private static WriteableBitmap LoadImage(byte[] pixels, int width, int height) { var bitmap = new WriteableBitmap(width, height); var buffer = bitmap.PixelBuffer; pixels.CopyTo(buffer); bitmap.Invalidate(); return bitmap; }
public object ToBitmap() { var bmp = new WriteableBitmap(Width, Heigth); // Copy data back using (var stream = System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.AsStream(bmp.PixelBuffer)) { stream.Write(Pixel, 0, Pixel.Length); } bmp.Invalidate(); return bmp; }
/// <summary> /// Copies the specified source bitmap into a new bitmap. /// </summary> /// <param name="source">The source bitmap.</param> /// <returns></returns> public static WriteableBitmap Copy(this WriteableBitmap source) { source.Invalidate(); var copiedBytes = new byte[4 * source.PixelWidth * source.PixelHeight]; var inputStream = source.PixelBuffer.AsStream(); inputStream.Seek(0, SeekOrigin.Begin); inputStream.Read(copiedBytes, 0, copiedBytes.Length); var target = new WriteableBitmap(source.PixelWidth, source.PixelHeight); var outputStream = target.PixelBuffer.AsStream(); outputStream.Seek(0, SeekOrigin.Begin); outputStream.Write(copiedBytes, 0, copiedBytes.Length); target.Invalidate(); return target; }
private void UpdateBitmap() { var resolutionScale = DisplayInformation.GetForCurrentView ().ResolutionScale; var screenScale = (float)resolutionScale / 100.0f; var width = (int)(ActualWidth * screenScale); var height = (int)(ActualHeight * screenScale); if (width == 0 || height == 0) return; IntPtr buff = Marshal.AllocCoTaskMem (width * height * 4); try { using (var surface = SKSurface.Create (width, height, SKImageInfo.PlatformColorType, SKAlphaType.Premul, buff, width * 4)) { var skcanvas = surface.Canvas; skcanvas.Scale (screenScale, screenScale); using (new SKAutoCanvasRestore (skcanvas, true)) { skiaView.SendDraw (skcanvas); } } var pixels = new byte[width * height * 4]; Marshal.Copy (buff, pixels, 0, pixels.Length); var bitmap = new WriteableBitmap (width, height); var stream = bitmap.PixelBuffer.AsStream (); stream.Seek (0, SeekOrigin.Begin); stream.Write (pixels, 0, pixels.Length); bitmap.Invalidate (); var b = bitmap; Background = new ImageBrush { ImageSource = b, AlignmentX = AlignmentX.Center, AlignmentY = AlignmentY.Center, Stretch = Stretch.Fill }; } finally { if (buff != IntPtr.Zero) { Marshal.FreeCoTaskMem (buff); } } }
/// <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 async Task LoadTexture(string filename) { var folder = Windows.ApplicationModel.Package.Current.InstalledLocation; var texFile = await folder.GetFileAsync(filename); var properties = await texFile.Properties.GetImagePropertiesAsync(); WriteableBitmap wbmp = new WriteableBitmap((Int32)properties.Width, (Int32)properties.Height); await wbmp.LoadAsync(texFile); byte[] pixels = new byte[wbmp.PixelWidth * wbmp.PixelHeight * 4]; using (Stream pixelStream = wbmp.PixelBuffer.AsStream()) { await pixelStream.ReadAsync(pixels, 0, pixels.Length); } wbmp.Invalidate(); TexturePixels = new Vector3[wbmp.PixelHeight, wbmp.PixelWidth]; int r = 0, c = 0; for (int i = 0; i < pixels.Length; i++) { TexturePixels[r, c] = new Vector3(pixels[i + 2], pixels[i + 1], pixels[i + 0]) / 255.0f; c = (c + 1) % wbmp.PixelWidth; if (c == 0) { r = (r + 1) % wbmp.PixelHeight; } i += 3; } TexSize = new Vector2(wbmp.PixelWidth, wbmp.PixelHeight); }
/// <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 static WriteableBitmap Crop(this WriteableBitmap source, int x1, int y1, int x2, int y2) { if (x1 >= x2 || y1 >= y2 || x1 < 0 || y1 < 0 || x2 < 0 || y2 < 0 || x1 > source.PixelWidth || y1 > source.PixelHeight || x2 > source.PixelWidth || y2 > source.PixelHeight) { throw new ArgumentException(); } //var buffer = source.PixelBuffer.GetPixels(); var cw = x2 - x1; var ch = y2 - y1; var target = new WriteableBitmap(cw, ch); var croppedBytes = new byte[4 * cw * ch]; var inputStream = source.PixelBuffer.AsStream(); inputStream.Seek(4 * (source.PixelWidth * y1 + x1), SeekOrigin.Current); for (int i = 0; i < ch; i++) { inputStream.Read(croppedBytes, 4 * cw * i, 4 * cw); inputStream.Seek(4 * (source.PixelWidth - cw), SeekOrigin.Current); } var outputStream = target.PixelBuffer.AsStream(); outputStream.Seek(0, SeekOrigin.Begin); outputStream.Write(croppedBytes, 0, croppedBytes.Length); target.Invalidate(); return target; }
private async Task LoadBitmap(IRandomAccessStream stream) { _writeableBitmap = new WriteableBitmap(1, 1); _writeableBitmap.SetSource(stream); _writeableBitmap.Invalidate(); await Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.Normal, () => ImageTarget.Source = _writeableBitmap); }
private static void OnThumbnailComplete(IImageProcessor processor, SoftwareBitmap softwareBitmap) { // Note: intentionally not awaited. We just deliver the thumbnail Bitmaps to the UI thread. TaskUtilities.RunOnDispatcherThreadAsync(() => { WriteableBitmap writeableBitmap = new WriteableBitmap(softwareBitmap.PixelWidth, softwareBitmap.PixelHeight); softwareBitmap.CopyToBuffer(writeableBitmap.PixelBuffer); writeableBitmap.Invalidate(); processor.ThumbnailImagSource = writeableBitmap; // The thumbnail image has been copied, so we can destroy the Bitmap. softwareBitmap.Dispose(); }); }
public async Task<WriteableBitmap> RenderToWriteableBitmap(FrameworkElement fe) { var width = (int)Math.Ceiling(fe.ActualWidth); var height = (int)Math.Ceiling(fe.ActualHeight); if (width == 0 || height == 0) { throw new InvalidOperationException("Can't render an empty element. ActualWidth or ActualHeight equal 0. Consider awaiting a WaitForNonZeroSizeAsync() call or invoking Measure()/Arrange() before the call to Render()."); } using (var renderTargetBitmap = CreateRenderTargetBitmap(width, height)) { _d2DDeviceContext.Target = renderTargetBitmap; _d2DDeviceContext.AntialiasMode = D2D.AntialiasMode.PerPrimitive; _d2DDeviceContext.TextAntialiasMode = D2D.TextAntialiasMode.Grayscale; await Compose(_d2DDeviceContext, fe); using (var cpuReadBitmap = CreateCpuReadBitmap(width, height)) { cpuReadBitmap.CopyFromRenderTarget( _d2DDeviceContext, new Point(0, 0), new SharpDX.Rectangle(0, 0, width, height)); var mappedRect = cpuReadBitmap.Map(D2D.MapOptions.Read); try { using (var readStream = new DataStream( userBuffer: mappedRect.DataPointer, sizeInBytes: mappedRect.Pitch * height, canRead: true, canWrite: false)) { var wb = new WriteableBitmap(width, height); using (var writeStream = wb.PixelBuffer.AsStream()) { var buffer = new byte[mappedRect.Pitch]; for (int i = 0; i < height; i++) { readStream.Read(buffer, 0, mappedRect.Pitch); writeStream.Write(buffer, 0, width * 4); } } wb.Invalidate(); return wb; } } finally { cpuReadBitmap.Unmap(); } } } }
private async void LoadWallpaperArt() { if (_loaded || !App.Locator.AppSettingsHelper.Read("WallpaperArt", true, SettingsStrategy.Roaming)) return; var wait = App.Locator.AppSettingsHelper.Read<int>("WallpaperDayWait"); var created = App.Locator.AppSettingsHelper.ReadJsonAs<DateTime>("WallpaperCreated"); // Set the image brush var imageBrush = new ImageBrush { Opacity = .25, Stretch = Stretch.UniformToFill, AlignmentY = AlignmentY.Top}; LayoutGrid.Background = imageBrush; // Once a week remake the wallpaper if ((DateTime.Now - created).TotalDays > wait) { var albums = App.Locator.CollectionService.Albums.ToList() .Where(p => p.HasArtwork) .ToList(); var albumCount = albums.Count; if (albumCount < 10) return; var h = Window.Current.Bounds.Height; var rows = (int) Math.Ceiling(h/(ActualWidth/5)); const int collumns = 5; var albumSize = (int) Window.Current.Bounds.Width/collumns; var numImages = rows*5; var imagesNeeded = numImages - albumCount; var shuffle = await Task.FromResult(albums .Shuffle() .Take(numImages > albumCount ? albumCount : numImages) .ToList()); if (imagesNeeded > 0) { var repeatList = new List<Album>(); while (imagesNeeded > 0) { var takeAmmount = imagesNeeded > albumCount ? albumCount : imagesNeeded; await Task.Run(() => repeatList.AddRange(shuffle.Shuffle().Take(takeAmmount))); imagesNeeded -= shuffle.Count; } shuffle.AddRange(repeatList); } // Initialize an empty WriteableBitmap. var destination = new WriteableBitmap((int) Window.Current.Bounds.Width, (int) Window.Current.Bounds.Height); var col = 0; // Current Column Position var row = 0; // Current Row Position destination.Clear(Colors.Black); // Set the background color of the image to black // will be copied foreach (var artworkPath in shuffle.Select(album => string.Format(AppConstant.ArtworkPath, album.Id))) { var file = await WinRtStorageHelper.GetFileAsync(artworkPath); // Read the image file into a RandomAccessStream using (var fileStream = await file.OpenReadAsync()) { try { // Now that you have the raw bytes, create a Image Decoder var decoder = await BitmapDecoder.CreateAsync(fileStream); // Get the first frame from the decoder because we are picking an image var frame = await decoder.GetFrameAsync(0); // Convert the frame into pixels var pixelProvider = await frame.GetPixelDataAsync(); // Convert pixels into byte array var srcPixels = pixelProvider.DetachPixelData(); var wid = (int) frame.PixelWidth; var hgt = (int) frame.PixelHeight; // Create an in memory WriteableBitmap of the same size var bitmap = new WriteableBitmap(wid, hgt); // Temporary bitmap into which the source using (var pixelStream = bitmap.PixelBuffer.AsStream()) { pixelStream.Seek(0, SeekOrigin.Begin); // Push the pixels from the original file into the in-memory bitmap await pixelStream.WriteAsync(srcPixels, 0, srcPixels.Length); bitmap.Invalidate(); // Resize the in-memory bitmap and Blit (paste) it at the correct tile // position (row, col) destination.Blit(new Rect(col*albumSize, row*albumSize, albumSize, albumSize), bitmap.Resize(albumSize, albumSize, WriteableBitmapExtensions.Interpolation.Bilinear), new Rect(0, 0, albumSize, albumSize)); col++; if (col < collumns) continue; row++; col = 0; } } catch { // ignored } } } var wallpaper = await WinRtStorageHelper.CreateFileAsync("wallpaper.jpg", ApplicationData.Current.LocalFolder); using (var rndWrite = await wallpaper.OpenAsync(FileAccessMode.ReadWrite)) { await destination.ToStreamAsJpeg(rndWrite); } App.Locator.AppSettingsHelper.WriteAsJson("WallpaperCreated", DateTime.Now); // If there are 30 or less albums then recreate in one day, else wait a week App.Locator.AppSettingsHelper.Write("WallpaperDayWait", albums.Count < 30 ? 1 : 7); imageBrush.ImageSource = null; imageBrush.ImageSource = new BitmapImage(new Uri("ms-appdata:/local/wallpaper.jpg")); } else if (created != DateTime.MinValue) { // Not the first time, so there must already be one created imageBrush.ImageSource = new BitmapImage(new Uri("ms-appdata:/local/wallpaper.jpg")); } _loaded = true; }
public async void DrawMandelbrot() { //this.Model.Calculate(); await ThreadPool.RunAsync(this.CalculateAsync); var bitmap = new WriteableBitmap((int)this.ImageWidth, (int)this.ImageHeight); byte[] buffer = new byte[4 * bitmap.PixelHeight * bitmap.PixelWidth]; foreach (var pixel in this.Model.Pixels) { int index = 4 * ((int)pixel.ScreenPos.Y * bitmap.PixelWidth + (int)pixel.ScreenPos.X); buffer[index + 0] = pixel.Color.Blue; buffer[index + 1] = pixel.Color.Green; buffer[index + 2] = pixel.Color.Red; buffer[index + 3] = pixel.Color.Alpha; } using (var stream = bitmap.PixelBuffer.AsStream()) { await stream.WriteAsync(buffer, 0, buffer.Length); } bitmap.Invalidate(); this.ImageSource = bitmap; }
/// <summary> /// This sets the new given stream with pixels to the bitmap /// and makes the ApplyReset stackPanel of the current popup to appear. /// </summary> /// <param name="givenStream"> Stream data to be written to the bitmap </param> /// <param name="givenBitmap"> Bitmap for saving the stream to </param> /// <param name="givenImage"> RemedyImage to display the bitmap </param> public void setStream(Stream givenStream, WriteableBitmap givenBitmap, RemedyImage givenImage) { givenStream.Seek(0, SeekOrigin.Begin); givenStream.Write(givenImage.dstPixels, 0, givenImage.dstPixels.Length); givenBitmap.Invalidate(); if (givenImage == image) { if (FiltersPopup.Popup.IsOpen) FiltersPopup.FilterApplyReset.Visibility = Visibility.Visible; else if (ColorsPopup.Popup.IsOpen) ColorsPopup.ColorApplyReset.Visibility = Visibility.Visible; else if (RotatePopup.Popup.IsOpen) RotatePopup.RotateApplyReset.Visibility = Visibility.Visible; else if (ExposurePopup.Popup.IsOpen) ExposurePopup.ExposureApplyReset.Visibility = Visibility.Visible; } }
/////////////////////////////////////////////////////////////////////////// // Use the Nokia Imaging SDK to apply a filter to a selected image private async void AppBarBtnEdit_Click(object sender, RoutedEventArgs e) { progressRing.IsEnabled = true; progressRing.IsActive = true; progressRing.Visibility = Visibility.Visible; // Create NOK Imaging SDK effects pipeline and run it var imageStream = new BitmapImageSource(originalBitmap.AsBitmap()); using (var effect = new FilterEffect(imageStream)) { var filter = new Lumia.Imaging.Adjustments.GrayscaleFilter(); effect.Filters = new[] { filter }; // Render the image to a WriteableBitmap. var renderer = new WriteableBitmapRenderer(effect, originalBitmap); editedBitmap = await renderer.RenderAsync(); editedBitmap.Invalidate(); } Image.Source = originalBitmap; Image.Visibility = Visibility.Collapsed; //Resizing the editedBitmap to 128x128 var resized1 = editedBitmap.Resize(128, 128, Windows.UI.Xaml.Media.Imaging.WriteableBitmapExtensions.Interpolation.Bilinear); //converting the editedBitmap to byte array byte[] edit_arr = resized1.ToByteArray(); //obtaining the images folder StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation; StorageFolder subfolder = await folder.GetFolderAsync("Images"); //create list of all the files in the images folder var pictures = await subfolder.GetFilesAsync(); double ldiff = 50;//least percentage difference for an image to be a match string dispText = "Try again";//default message to be displayed byte threshold = 124; //process through all images foreach (var file in pictures) { if (file != null) { // Use WriteableBitmapEx to easily load image from a stream using (var stream = await file.OpenReadAsync()) { listBitmap = await new WriteableBitmap(1, 1).FromStream(stream); stream.Dispose(); } //convert obtained image to byte array byte[] list_arr = listBitmap.ToByteArray(); byte[] difference = new byte[edit_arr.Length]; //compare byte array of both the images for (int i=0;i<list_arr.Length;i++) { difference[i] = (byte)Math.Abs(edit_arr[i]-list_arr[i]); } //calculate percentage difference int differentPixels = 0; foreach(byte b in difference ) { if (b > threshold) differentPixels++; } double percentage = (double)differentPixels / (double)list_arr.Length; percentage = percentage * 100; if (percentage <= ldiff) { ldiff = percentage; dispText =file.DisplayName; } } } tb.Text = dispText; progressRing.IsEnabled = false; progressRing.IsActive = false; progressRing.Visibility = Visibility.Collapsed; tb.Visibility = Visibility.Visible; Image.Visibility = Visibility.Visible; var tmp = new RenderTargetBitmap(); await tmp.RenderAsync(source); var buffer = await tmp.GetPixelsAsync(); var width = tmp.PixelWidth; var height = tmp.PixelHeight; editedBitmap = await new WriteableBitmap(1, 1).FromPixelBuffer(buffer, width, height); AppBarBtnSpeech.IsEnabled = true; AppBarBtnSpeech.Visibility = Visibility.Visible; AppBarBtnSave.IsEnabled = true; }
private async Task DoRender(IReadOnlyList<IImageProvider> imageProviders, int animationIndex, bool renderBackground = false) { if (_onScreenImageProviders[animationIndex] != null) { int imageWidth = imageProviders == _unalignedImageProviders ? _unalignedImageWidth : _alignedImageWidth; int imageHeight = imageProviders == _unalignedImageProviders ? _unalignedImageHeight : _alignedImageHeight; if (_foregroundBitmap == null || _foregroundBitmap.PixelWidth != imageWidth || _foregroundBitmap.PixelHeight != imageHeight) _foregroundBitmap = new WriteableBitmap(imageWidth, imageHeight); using (WriteableBitmapRenderer writeableBitmapRenderer = new WriteableBitmapRenderer(imageProviders[animationIndex], _foregroundBitmap)) { _foregroundBitmap = await writeableBitmapRenderer.RenderAsync(); } if (renderBackground) { if (_backgroundBitmap == null || _backgroundBitmap.PixelWidth != imageWidth || _backgroundBitmap.PixelHeight != imageHeight) _backgroundBitmap = new WriteableBitmap(imageWidth, imageHeight); using (WriteableBitmapRenderer writeableBitmapRenderer = new WriteableBitmapRenderer(imageProviders[0], _backgroundBitmap)) { _backgroundBitmap = await writeableBitmapRenderer.RenderAsync(); } } await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { _foregroundBitmap.Invalidate(); ImageElement.Source = _foregroundBitmap; if (renderBackground) { _backgroundBitmap.Invalidate(); ImageElementBackground.Source = _backgroundBitmap; } }); } }
private async void M_videoTimer_Tick(object sender, object e) { if (m_mediaCapture == null) { m_videoTimer.Stop(); m_videoTimer = null; return; } lock(m_mediaCapture) { if(isrunning) { return; } isrunning = true; } LowLagPhotoCapture cap = await m_mediaCapture.PrepareLowLagPhotoCaptureAsync(ImageEncodingProperties.CreateBmp()); CapturedPhoto photo = await cap.CaptureAsync(); WriteableBitmap bitmap = new WriteableBitmap((int)photo.Frame.Width, (int)photo.Frame.Height); await bitmap.SetSourceAsync(photo.Frame.AsStreamForRead().AsRandomAccessStream()); bitmap.Invalidate(); byte[] imageArray = bitmap.PixelBuffer.ToArray(); int starting = (bitmap.PixelHeight /2) * bitmap.PixelWidth * 4 + (bitmap.PixelWidth * 2); byte blue = imageArray[starting]; byte green = imageArray[starting+1]; byte red = imageArray[starting+2]; m_liveColor[0, 0] = red; m_liveColor[0, 1] = green; m_liveColor[0, 2] = blue; MakeLiveSettingsUpdate(); isrunning = false; }
async Task CreateCollage() { var sampleDataGroups = this._allGroups; if (sampleDataGroups.Count() > 0 && sampleDataGroups.ToList()[0].TopItems.Count() == 0) return; List<TwitterList> list = sampleDataGroups.ToList(); foreach (var currentList in list) { try { IEnumerable<TweetItem> topItems = currentList.TopItems; List<Uri> uris = (from tweetItem in topItems select ((BitmapImage)tweetItem.Image).UriSource).ToList<Uri>(); if (uris.Count > 0) { int number = (int)Math.Ceiling(Math.Sqrt((double)uris.Count)); WriteableBitmap destination = new WriteableBitmap(48 * number, 48 * number); int col = 0; int row = 0; destination.Clear(Colors.Transparent); WriteableBitmap bitmap; foreach (var uri1 in uris) { RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromUri(uri1); int wid = 0; int hgt = 0; byte[] srcPixels; using (IRandomAccessStreamWithContentType fileStream = await streamRef.OpenReadAsync()) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream); BitmapFrame frame = await decoder.GetFrameAsync(0); PixelDataProvider pixelProvider = await frame.GetPixelDataAsync(); srcPixels = pixelProvider.DetachPixelData(); wid = (int)frame.PixelWidth; hgt = (int)frame.PixelHeight; bitmap = new WriteableBitmap(wid, hgt); } Stream pixelStream1 = bitmap.PixelBuffer.AsStream(); pixelStream1.Seek(0, SeekOrigin.Begin); pixelStream1.Write(srcPixels, 0, (int)srcPixels.Length); bitmap.Invalidate(); if (row < number) { destination.Blit(new Rect(col * wid, row * hgt, wid, hgt), bitmap, new Rect(0, 0, wid, hgt)); col++; if (col >= number) { row++; col = 0; } } } currentList.Image = destination; ((WriteableBitmap)currentList.Image).Invalidate(); } } catch (Exception ex) { // TODO: Log Error, unable to render image } } }
public static void SaveJpeg(this BitmapSource bitmap, Stream output, int width, int height, bool saveRatio) { int pixelWidth; int pixelHeight; double actualFactor = bitmap.PixelWidth / ((double)bitmap.PixelHeight); double desiredFactor = width / ((double)height); if (saveRatio) { if (actualFactor < desiredFactor) { pixelWidth = bitmap.PixelWidth; pixelHeight = (int)(pixelWidth / desiredFactor); } else { pixelHeight = bitmap.PixelHeight; pixelWidth = (int)(pixelHeight * desiredFactor); } } else { pixelWidth = bitmap.PixelWidth; pixelHeight = bitmap.PixelHeight; } var bitmap2 = new WriteableBitmap(pixelWidth, pixelHeight); bitmap2.Invalidate(); var bitmap3 = new WriteableBitmap(pixelWidth, pixelHeight); if (pixelWidth == bitmap.PixelWidth) { System.Buffer.BlockCopy(bitmap2.PixelBuffer.ToArray(), 0, bitmap3.PixelBuffer.ToArray(), 0, (pixelWidth * pixelHeight) * 4); } else { int srcOffset = 0; int dstOffset = 0; for (int i = 0; i < pixelHeight; i++) { System.Buffer.BlockCopy(bitmap2.PixelBuffer.ToArray(), srcOffset, bitmap3.PixelBuffer.ToArray(), dstOffset, pixelWidth * 4); srcOffset += bitmap.PixelWidth * 4; dstOffset += pixelWidth * 4; } } // bitmap3.SaveJpeg(output, width, height, 0, 100); }
private async Task DrawDepthCoodinate() { // Depth画像の解像度でデータを作る var colorImageBuffer = new byte[depthFrameDesc.LengthInPixels * colorFrameDesc.BytesPerPixel]; // 変換処理が重いため、非同期に行う await Task.Factory.StartNew( () => { // Depth座標系に対応するカラー座標系の一覧を取得する var colorSpace = new ColorSpacePoint[depthFrameDesc.LengthInPixels]; kinect.CoordinateMapper.MapDepthFrameToColorSpace( depthBuffer, colorSpace ); // 並列で処理する Parallel.For( 0, depthFrameDesc.LengthInPixels, i => { int colorX = (int)colorSpace[i].X; int colorY = (int)colorSpace[i].Y; if ( (colorX < 0) || (colorFrameDesc.Width <= colorX) || (colorY < 0) || (colorFrameDesc.Height <= colorY) ) { return; } // カラー座標系のインデックス int colorIndex = (colorY * colorFrameDesc.Width) + colorX; int bodyIndex = bodyIndexBuffer[i]; // 人を検出した位置だけ色を付ける if ( bodyIndex == 255 ) { return; } // カラー画像を設定する int colorImageIndex = (int)(i * colorFrameDesc.BytesPerPixel); int colorBufferIndex = (int)(colorIndex * colorFrameDesc.BytesPerPixel); colorImageBuffer[colorImageIndex + 0] = colorBuffer[colorBufferIndex + 0]; colorImageBuffer[colorImageIndex + 1] = colorBuffer[colorBufferIndex + 1]; colorImageBuffer[colorImageIndex + 2] = colorBuffer[colorBufferIndex + 2]; } ); } ); // ビットマップにする var colorBitmap = new WriteableBitmap( depthFrameDesc.Width, depthFrameDesc.Height ); var stream = colorBitmap.PixelBuffer.AsStream(); stream.Write( colorImageBuffer, 0, colorImageBuffer.Length ); colorBitmap.Invalidate(); ImageColor.Source = colorBitmap; }
async Task CreateCollage(IReadOnlyList<StorageFile> files) { progressIndicator.Visibility = Windows.UI.Xaml.Visibility.Visible; var sampleDataGroups = files; if (sampleDataGroups.Count() == 0) return; try { // Do a square-root of the number of images to get the // number of images on x and y axis int number = (int)Math.Ceiling(Math.Sqrt((double)files.Count)); // Calculate the width of each small image in the collage int numberX = (int)(ImageCollage.ActualWidth / number); int numberY = (int)(ImageCollage.ActualHeight / number); // Initialize an empty WriteableBitmap. WriteableBitmap destination = new WriteableBitmap(numberX * number, numberY * number); int col = 0; // Current Column Position int row = 0; // Current Row Position destination.Clear(Colors.White); // Set the background color of the image to white WriteableBitmap bitmap; // Temporary bitmap into which the source // will be copied foreach (var file in files) { // Create RandomAccessStream reference from the current selected image RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromFile(file); int wid = 0; int hgt = 0; byte[] srcPixels; // Read the image file into a RandomAccessStream using (IRandomAccessStreamWithContentType fileStream = await streamRef.OpenReadAsync()) { // Now that you have the raw bytes, create a Image Decoder BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream); // Get the first frame from the decoder because we are picking an image BitmapFrame frame = await decoder.GetFrameAsync(0); // Convert the frame into pixels PixelDataProvider pixelProvider = await frame.GetPixelDataAsync(); // Convert pixels into byte array srcPixels = pixelProvider.DetachPixelData(); wid = (int)frame.PixelWidth; hgt = (int)frame.PixelHeight; // Create an in memory WriteableBitmap of the same size bitmap = new WriteableBitmap(wid, hgt); Stream pixelStream = bitmap.PixelBuffer.AsStream(); pixelStream.Seek(0, SeekOrigin.Begin); // Push the pixels from the original file into the in-memory bitmap pixelStream.Write(srcPixels, 0, (int)srcPixels.Length); bitmap.Invalidate(); if (row < number) { // Resize the in-memory bitmap and Blit (paste) it at the correct tile // position (row, col) destination.Blit(new Rect(col * numberX, row * numberY, numberX, numberY), bitmap.Resize(numberX, numberY, WriteableBitmapExtensions.Interpolation.Bilinear), new Rect(0, 0, numberX, numberY)); col++; if (col >= number) { row++; col = 0; } } } } ImageCollage.Source = destination; ((WriteableBitmap)ImageCollage.Source).Invalidate(); progressIndicator.Visibility = Windows.UI.Xaml.Visibility.Collapsed; } catch (Exception ex) { // TODO: Log Error, unable to render image throw; } }
async private Task updateImage(WriteableBitmap bitmap, byte[] newPixels) { using (Stream stream = bitmap.PixelBuffer.AsStream()) { await stream.WriteAsync(newPixels, 0, newPixels.Length); } bitmap.Invalidate(); }
/// <summary> /// Copies the bitmap into a new WriteableBitmap. This method can only be called in the CoreDispatcher synchronization context. /// </summary> /// <param name="bitmap">Source bitmap. Must have ColorMode.Bgra8888.</param> /// <returns></returns> /// <remarks> /// This special case operation can be useful when the time spent in the dispatcher thread should be kept to a minimum, at the cost of the memory consumed by two copies of the image. /// <para> /// For example: a number of thumbnails must be generated and displayed in a XAML UI. BitmapRenderers are to generate the Bitmaps, doing all the actual rendering in the ThreadPool. /// The final conversions from Bitmaps to WriteableBitmaps are done using CoreDispatcher.RunAsync and calling this method. /// </para> /// </remarks> public static WriteableBitmap ToWriteableBitmap(this Bitmap bitmap) { var firstBuffer = bitmap.Buffers[0]; var sourcePixels = firstBuffer.Buffer; var bitmapWidth = (int)bitmap.Dimensions.Width; var bitmapHeight = (int)bitmap.Dimensions.Height; var writeableBitmap = new WriteableBitmap(bitmapWidth, bitmapHeight); if (bitmap.ColorMode != ColorMode.Bgra8888) { throw new ArgumentException("The source Bitmap must have ColorMode.Bgra8888."); } var bitmapWidthBytes = (uint)(4 * bitmapWidth); var writeableBitmapBuffer = writeableBitmap.PixelBuffer; uint pitch = firstBuffer.Pitch; if (pitch == bitmapWidthBytes) { sourcePixels.CopyTo(0U, writeableBitmapBuffer, 0U, (uint)(bitmapWidthBytes*bitmapHeight)); } else { for (int y = 0; y < bitmapHeight; ++y) { sourcePixels.CopyTo((uint)(y * pitch), writeableBitmapBuffer, (uint)(y * bitmapWidthBytes), bitmapWidthBytes); } } writeableBitmap.Invalidate(); return writeableBitmap; }
async void LoadImage(string fileName,string option) { // Open the file StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx://" + fileName)); using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) { // We have to load the file in a BitmapImage first, so we can check the width and height.. BitmapImage bmp = new BitmapImage(); bmp.SetSource(fileStream); // Load the picture in a WriteableBitmap WriteableBitmap writeableBitmap = new WriteableBitmap(bmp.PixelWidth, bmp.PixelHeight); writeableBitmap.SetSource(await file.OpenAsync(Windows.Storage.FileAccessMode.Read)); // Now we have to extract the pixels from the writeablebitmap // Get all pixel colors from the buffer pixelColors = writeableBitmap.PixelBuffer.ToArray(); // passbyte = pixelColors; bytesAsInts = conversion1.GetIntArrayFromByteArray(pixelColors); // txtbox.Text += 0.5; if (option == Convert.ToString(1)) { if (check12) { resultbyte = passbyte; check12 = false; } bool check122 = false; if (resultbyte != null && check1) { bytesAsInts = conversion1.GetIntArrayFromByteArray(resultbyte); check122 = true; } else { bytesAsInts = conversion1.GetIntArrayFromByteArray(pixelColors); } resultarray = bg.Process(bytesAsInts, bmp.PixelWidth, bmp.PixelHeight); passbyte = conversion1.GetByteArrayFromIntArray(resultarray); if (check122) { check1 = true; } else { check1 = false; } check2 = true; check3 = true; check22 = true; check32 = true; check4 = true; check42 = true; // Now we have to write back our pixel colors to the writeable bitmap.. } else if (option == Convert.ToString(2)) { bool check222 = false; if (check22) { resultbyte = passbyte; check22 = false; } if (resultbyte != null && check2) { Saturation st = new Saturation(); passbyte = st.satura(resultbyte, bmp.PixelWidth, bmp.PixelHeight, sature); check222 = true; } else { Saturation st = new Saturation(); passbyte = st.satura(pixelColors, bmp.PixelWidth, bmp.PixelHeight, sature); } if (check222) { check2 = true; } else { check2 = false; } check12 = true; check32 = true; check3 = true; check1 = true; check4 = true; check42 = true; } else if (option == Convert.ToString(3)) { resultarray = Bitmap_Sharpen.sharpen(bytesAsInts, bmp.PixelWidth, bmp.PixelHeight, sharp); passbyte = conversion1.GetByteArrayFromIntArray(resultarray); resultbyte = passbyte; } else if (option == Convert.ToString(4)) { bool check333 = false; if (check32) { resultbyte = passbyte; check32 = false; } if (resultbyte != null && check3) { Gamma gam = new Gamma(); passbyte = gam.GammaChange(resultbyte, bmp.PixelWidth, bmp.PixelHeight, gamma); check333 = true; } else { check333 = false; Gamma gam = new Gamma(); passbyte = gam.GammaChange(pixelColors, bmp.PixelWidth, bmp.PixelHeight, gamma); } if (check333) { check3 = true; } else { check3 = false; } check12 = true; check22 = true; check2 = true; check1 = true; check4 = true; check42 = true; } else if (option == Convert.ToString(5)) { //hue code bool check444 = false; if (check42) { resultbyte = passbyte; check42 = false; } if (resultbyte != null && check4 == true) { writeableBitmap.PixelBuffer.AsStream().Write(passbyte, 0, passbyte.Length); writeableBitmap = ChangeHue.ChangeHue1(writeableBitmap, amount); check444 = true; } else { writeableBitmap = ChangeHue.ChangeHue1(writeableBitmap, amount); } resultbyte = writeableBitmap.PixelBuffer.ToArray(); passbyte = resultbyte; if (check444) { check4 = true; } else { check4 = false; } check12 = true; check22 = true; check2 = true; check1 = true; check3 = true; check32 = true; } writeableBitmap.PixelBuffer.AsStream().Write(passbyte, 0, passbyte.Length); // Set the source of our image to the WriteableBitmap img1.Source = writeableBitmap; //img1.Source = wb; // Tell the image it needs a redraw writeableBitmap.Invalidate(); } }
/// <summary> /// Detects the color order of a stored byte array. Byte order may change between platforms, you should call this once before writting a PNG or if you have any issues with colors changing. /// </summary> public static void DetectWBByteOrder() { // We should only ever run the detection once (assuming it succeeded at least). if (WBBODetectionRun == true) { return; } // Create a 3x1 WriteableBitmap to write RGB colors to. var TestWB = new WriteableBitmap(3, 1); //// Create the red 1 pixel rectangle. //var redRectangle = new Rectangle(); //redRectangle.Width = 1; //redRectangle.Height = 1; //redRectangle.Fill = new SolidColorBrush( Colors.Red ); //// Create the green 1 pixel rectangle. //var greenRectangle = new Rectangle(); //greenRectangle.Width = 1; //greenRectangle.Height = 1; //greenRectangle.Fill = new SolidColorBrush( Colors.Green ); //// Create the blue 1 pixel rectangle. //var blueRectangle = new Rectangle(); //blueRectangle.Width = 1; //blueRectangle.Height = 1; //blueRectangle.Fill = new SolidColorBrush( Colors.Blue ); // Render the three 1 px rectangles. TestWB.SetPixel(0, 0, Colors.Red); TestWB.SetPixel(1, 0, Colors.Green); TestWB.SetPixel(2, 0, Colors.Blue); // Invalidate the bitmap to make it actually render. TestWB.Invalidate(); // Go get the 4 byte arrays of each red/green/blue pixels that we just rendered. var redColor = TestWB.GetPixel(0, 0); var greenColor = TestWB.GetPixel(1, 0); var blueColor = TestWB.GetPixel(2, 0); byte[] redBytes = { redColor.A, redColor.R, redColor.G, redColor.B }; byte[] greenBytes = { greenColor.A, greenColor.R, greenColor.G, greenColor.B }; byte[] blueBytes = { blueColor.A, blueColor.R, blueColor.G, blueColor.B }; // Just in case something goes terrible wrong, set all the color values to invalid settings. int trans = 4; int red = 4; int green = 4; int blue = 4; // Find the alpha channel, this wil be the only byte that is the same in all three pixels. if (redBytes[0] == greenBytes[0] && blueBytes[0] == greenBytes[0]) { trans = 0; } if (redBytes[1] == greenBytes[1] && blueBytes[1] == greenBytes[1]) { trans = 1; } if (redBytes[2] == greenBytes[2] && blueBytes[2] == greenBytes[2]) { trans = 2; } if (redBytes[3] == greenBytes[3] && blueBytes[3] == greenBytes[3]) { trans = 3; } // if we didn't detect the alpha channel, just give up :( if (trans != 4) { // now set all the alpha channel's to zero to get them out of the way. redBytes[trans] = 0; greenBytes[trans] = 0; blueBytes[trans] = 0; // Find the red channel. if (redBytes[0] == 255) { red = 0; } else if (redBytes[1] == 255) { red = 1; } else if (redBytes[2] == 255) { red = 2; } else if (redBytes[3] == 255) { red = 3; } // Find the green channel, note that Colors.Green is not dark green, but light green so use 128 instead of 255 to detect it. if (greenBytes[0] == 128) { green = 0; } else if (greenBytes[1] == 128) { green = 1; } else if (greenBytes[2] == 128) { green = 2; } else if (greenBytes[3] == 128) { green = 3; } // Find the blue channel. if (blueBytes[0] == 255) { blue = 0; } else if (blueBytes[1] == 255) { blue = 1; } else if (blueBytes[2] == 255) { blue = 2; } else if (blueBytes[3] == 255) { blue = 3; } } // Now set the byte order, if any of the values are still set to 4, something went wrong and return the default values. if (red == 4 || green == 4 || blue == 4 || trans == 4) { WBByteOrder = new int[] { 2, 1, 0, 3 }; } else { WBBODetectionRun = true; WBByteOrder = new int[] { red, green, blue, trans }; } }
/// <summary> /// Copies the bitmap contents into an existing WriteableBitmap. This method can only be called in the CoreDispatcher synchronization context. /// </summary> /// <param name="bitmap">Source Bitmap. Must have ColorMode.Bgra8888.</param> /// <param name="writeableBitmap">Target WriteableBitmap. Must be the same dimensions as the source Bitmap.</param> /// <returns></returns> /// <remarks> /// This special case operation can be useful when the time spent in the dispatcher thread should be kept to a minimum, at the cost of the memory consumed by two copies of the image. /// <para> /// For example: a number of thumbnails must be generated and displayed in a XAML UI. BitmapRenderers are to generate the Bitmaps, doing all the actual rendering in the ThreadPool. /// The final conversions from Bitmaps to WriteableBitmaps are done using CoreDispatcher.RunAsync and calling this method. /// </para> /// </remarks> public static void CopyTo(this Bitmap bitmap, WriteableBitmap writeableBitmap) { if (bitmap == null) throw new ArgumentNullException("bitmap"); if (writeableBitmap == null) throw new ArgumentNullException("writeableBitmap"); var firstBuffer = bitmap.Buffers[0]; var bitmapWidth = (int)bitmap.Dimensions.Width; var bitmapHeight = (int)bitmap.Dimensions.Height; if (bitmapWidth != writeableBitmap.PixelWidth || bitmapHeight != writeableBitmap.PixelHeight) { throw new ArgumentException("The WriteableBitmap must have the same dimensions as the Bitmap."); } if (bitmap.ColorMode != ColorMode.Bgra8888) { throw new ArgumentException("The source Bitmap must have ColorMode.Bgra8888."); } var bitmapWidthBytes = (uint)(4 * bitmapWidth); var sourcePixels = firstBuffer.Buffer; var writeableBitmapBuffer = writeableBitmap.PixelBuffer; uint pitch = firstBuffer.Pitch; if (pitch == bitmapWidthBytes) { sourcePixels.CopyTo(0U, writeableBitmapBuffer, 0U, (uint) (bitmapWidthBytes*bitmapHeight)); } else { for (int y = 0; y < bitmapHeight; ++y) { sourcePixels.CopyTo((uint) (y*pitch), writeableBitmapBuffer, (uint) (y*bitmapWidthBytes), bitmapWidthBytes); } } writeableBitmap.Invalidate(); }
private async Task<bool> ApplyFilterAsync(StorageFile file) { // Open a stream for the selected file. IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read); string errorMessage = null; try { // Show thumbnail of original image. _thumbnailImageBitmap.SetSource(fileStream); OriginalImage.Source = _thumbnailImageBitmap; // Rewind stream to start. fileStream.Seek(0); // A cartoon effect is initialized with selected image stream as source. var imageStream = new RandomAccessStreamImageSource(fileStream); _cartoonEffect = new FilterEffect(imageStream); // Add the cartoon filter as the only filter for the effect. var cartoonFilter = new CartoonFilter(); _cartoonEffect.Filters = new[] { cartoonFilter }; // Render the image to a WriteableBitmap. var renderer = new WriteableBitmapRenderer(_cartoonEffect, _cartoonImageBitmap); _cartoonImageBitmap = await renderer.RenderAsync(); _cartoonImageBitmap.Invalidate(); // Set the rendered image as source for the cartoon image control. CartoonImage.Source = _cartoonImageBitmap; } catch (Exception exception) { errorMessage = exception.Message; } if (!string.IsNullOrEmpty(errorMessage)) { var dialog = new MessageDialog(errorMessage); await dialog.ShowAsync(); return false; } return true; }