/// <summary> /// Dissolves two images using alphablending /// </summary> /// <param name="startImage">Image for percentage=0</param> /// <param name="endImage">Image for percentage=1</param> /// <param name="morphingProgress">Dissolve percentage from 0 to 1</param> /// <param name="outputImage">Target for image output data</param> public unsafe void DissolveImages(Morphing.ImageData startImage, Morphing.ImageData endImage, float percentage, WriteableBitmap outputImage) { System.Diagnostics.Debug.Assert(percentage >= 0.0f && percentage <= 1.0f); System.Diagnostics.Debug.Assert(startImage != null && endImage != null && outputImage != null); outputImage.Lock(); int width = outputImage.PixelWidth; int height = outputImage.PixelHeight; float xStep = 1.0f / width; Color* outputData = (Color*)outputImage.BackBuffer; Parallel.For(0, outputImage.PixelHeight, yi => { Color* outputDataPixel = outputData + yi * width; Color* lastOutputDataPixel = outputDataPixel + width; float y = (float)yi / height; for (float x = 0; outputDataPixel != lastOutputDataPixel; x += xStep, ++outputDataPixel) { *outputDataPixel = Color.Lerp(startImage.Sample(x, y), endImage.Sample(x, y), percentage); } }); outputImage.AddDirtyRect(new System.Windows.Int32Rect(0, 0, outputImage.PixelWidth, outputImage.PixelHeight)); outputImage.Unlock(); }
protected override void OnRender(DrawingContext drawingContext) { base.OnRender(drawingContext); if (sample == null) return; var m = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice; var dpiX = m.M11; var dpiY = m.M22; int width = (int)(ActualWidth * dpiX); int height = (int)(ActualHeight * dpiY); var bitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Pbgra32, null); bitmap.Lock(); using (var surface = SKSurface.Create(width, height, SKImageInfo.PlatformColorType, SKAlphaType.Premul, bitmap.BackBuffer, bitmap.BackBufferStride)) { var skcanvas = surface.Canvas; skcanvas.Scale((float)dpiX, (float)dpiY); using (new SKAutoCanvasRestore(skcanvas, true)) { sample.Method(skcanvas, (int)ActualWidth, (int)ActualHeight); } } bitmap.AddDirtyRect(new Int32Rect(0, 0, width, height)); bitmap.Unlock(); drawingContext.DrawImage(bitmap, new Rect(0, 0, ActualWidth, ActualHeight)); }
public override void UpdateNormalBitmap(WriteableBitmap bitmap, Color color) { unsafe { bitmap.Lock(); int currentPixel = -1; byte* pStart = (byte*)(void*)bitmap.BackBuffer; double iRowUnit = (double)1 / 256; double iRowCurrent = 1; double hue = sModel.HComponent(color); double saturation = sModel.SComponent(color); for (int iRow = 0; iRow < bitmap.PixelHeight; iRow++) { Color hueColor = sModel.Color(hue, saturation, iRowCurrent); for (int iCol = 0; iCol < bitmap.PixelWidth; iCol++) { currentPixel++; *(pStart + currentPixel * 3 + 0) = hueColor.B; //Blue *(pStart + currentPixel * 3 + 1) = hueColor.G; //Green *(pStart + currentPixel * 3 + 2) = hueColor.R; //red } iRowCurrent -= iRowUnit; } bitmap.AddDirtyRect(new Int32Rect(0, 0, bitmap.PixelWidth, bitmap.PixelHeight)); bitmap.Unlock(); } }
//public void MarkFrequency(float frequency, WriteableBitmap output) //{ // if(this.soundSpectrum != null) // { // var renderAreaHeight = output.PixelHeight; // var renderAreaWidth = output.PixelWidth; // var slotIndex = (int)(Math.Round(((frequency - this.spectrumStartFrequency) / (this.spectrumEndFrequency - this.spectrumStartFrequency)) * renderAreaWidth)); // if(slotIndex < output.PixelWidth && slotIndex >= 0) // { // output.Lock(); // this.RenderAtSlot(slotIndex, 1.0f, output, Colors.Red); // output.AddDirtyRect(new Int32Rect(slotIndex, 0, 1, renderAreaHeight)); // output.Unlock(); // } // } //} public void MarkFrequency(float frequency, WriteableBitmap output) { if (this.soundSpectrum != null) { var renderAreaHeight = output.PixelHeight; var renderAreaWidth = output.PixelWidth; var diff = this.spectrumEndFrequency - this.spectrumStartFrequency; //var slotIndex = (int)(((frequency - this.spectrumStartFrequency) / diff) * renderAreaWidth); var slotIndex = (int)Math.Round(frequency / binFrequency); var startBin = (int)Math.Round(this.spectrumStartFrequency / binFrequency); slotIndex -= startBin; slotIndex = (int)Math.Round(((float)slotIndex / this.soundSpectrum.Length) * renderAreaWidth); if (slotIndex < output.PixelWidth && slotIndex >= 0) { output.Lock(); this.RenderAtSlot(slotIndex, 1.0f, output, Colors.Red); output.AddDirtyRect(new Int32Rect(0, 0, renderAreaWidth, renderAreaHeight)); //output.AddDirtyRect(new Int32Rect(slotIndex, 0, 1, renderAreaHeight)); output.Unlock(); } } }
public virtual void DrawPixel(ref WriteableBitmap writeableBitmap, int x, int y) { int column = x; int row = y; // Reserve the back buffer for updates. writeableBitmap.Lock(); unsafe { // Get a pointer to the back buffer. int pBackBuffer = (int)writeableBitmap.BackBuffer; // Find the address of the pixel to draw. pBackBuffer += row * writeableBitmap.BackBufferStride; pBackBuffer += column * 4; // Compute the pixel's color. int color_data = 255 << 16; // R color_data |= 255 << 8; // G color_data |= 255 << 0; // B // Assign the color data to the pixel. *((int*)pBackBuffer) = color_data; } // Specify the area of the bitmap that changed. writeableBitmap.AddDirtyRect(new Int32Rect(column, row, 1, 1)); // Release the back buffer and make it available for display. writeableBitmap.Unlock(); }
public Window1() { InitializeComponent(); SnapsToDevicePixels = true; SizeToContent = SizeToContent.WidthAndHeight; var i = new Image { Width = MandelbrotProvider.DefaultWidth, Height = MandelbrotProvider.DefaultHeight }; var s = new WriteableBitmap(MandelbrotProvider.DefaultWidth, MandelbrotProvider.DefaultHeight, // dpi does not seem to matter at this point 96, 96, PixelFormats.Pbgra32, null); var shift = 0; Action Refresh = delegate { var buffer = MandelbrotProvider.DrawMandelbrotSet(shift); s.Lock(); for (int j = 0; j < buffer.Length; j++) { Marshal.WriteInt32(s.BackBuffer, j * 4, unchecked((int)((uint)buffer[j] | 0xff000000))); } s.AddDirtyRect(new Int32Rect(0, 0, MandelbrotProvider.DefaultWidth, MandelbrotProvider.DefaultHeight)); s.Unlock(); }; var t = new DispatcherTimer(); t.Tick += delegate { shift++; Refresh(); }; t.Interval = TimeSpan.FromMilliseconds(10); t.Start(); Refresh(); i.Source = s; this.Content = i; }
public static void Main(string[] args) { Console.WriteLine(""); if (args.Length < 2) usage(); mapObj map = new mapObj(args[0]); Console.WriteLine("# Map layers " + map.numlayers + "; Map name = " + map.name); for (int i = 0; i < map.numlayers; i++) { Console.WriteLine("Layer [" + i + "] name: " + map.getLayer(i).name); } try { WriteableBitmap mapImage = new WriteableBitmap(map.width, map.height, 96, 96, PixelFormats.Bgr32, null); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); using (imageObj image = map.draw()) { // Reserve the back buffer for updates. mapImage.Lock(); try { if (image.getRawPixels(mapImage.BackBuffer) == (int)MS_RETURN_VALUE.MS_FAILURE) { Console.WriteLine("Unable to get image contents"); } // Specify the area of the bitmap that changed. mapImage.AddDirtyRect(new Int32Rect(0, 0, map.width, map.height)); } finally { // Release the back buffer and make it available for display. mapImage.Unlock(); } Console.WriteLine("Rendering time: " + stopwatch.ElapsedMilliseconds + "ms"); // Save the bitmap into a file. using (FileStream stream = new FileStream(args[1], FileMode.Create)) { PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(mapImage)); encoder.Save(stream); } } } catch (Exception ex) { Console.WriteLine( "\nMessage ---\n{0}", ex.Message ); Console.WriteLine( "\nHelpLink ---\n{0}", ex.HelpLink ); Console.WriteLine( "\nSource ---\n{0}", ex.Source ); Console.WriteLine( "\nStackTrace ---\n{0}", ex.StackTrace ); Console.WriteLine( "\nTargetSite ---\n{0}", ex.TargetSite ); } }
public static WriteableBitmap GetImage(string path, int width, int height) { // Y,Cb,Crのbyte列を取得 byte[] lum, cb, cr; int ret; using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { // byte列の確保 lum = new byte[fs.Length / 2]; cb = new byte[lum.Length / 2]; cr = new byte[lum.Length / 2]; // 読込み ret = fs.Read(lum, 0, lum.Length); ret = fs.Read(cr, 0, cr.Length); ret = fs.Read(cb, 0, cb.Length); } double temp; WriteableBitmap wbmp = new WriteableBitmap( width, height, 96, 96, PixelFormats.Bgr32, null); wbmp.Lock(); byte[] buf = new byte[wbmp.PixelWidth * wbmp.PixelHeight * 4]; for (int i = 0; i < buf.Length; i += 4) { int index = i / 4; // B temp = 1.164 * (lum[index] - 16) + 2.018 * (cr[index / 2] - 128); if (temp > 255) temp = 255; if (temp < 0) temp = 0; buf[i] = (byte)temp; // G temp = 1.164 * (lum[index] - 16) - 0.391 * (cr[index / 2] - 128) - 0.813 * (cb[index / 2] - 128); if (temp > 255) temp = 255; if (temp < 0) temp = 0; buf[i + 1] = (byte)temp; // R temp = 1.164 * (lum[index] - 16) + 1.596 * (cb[index / 2] - 128); if (temp > 255) temp = 255; if (temp < 0) temp = 0; buf[i + 2] = (byte)temp; } Marshal.Copy(buf, 0, wbmp.BackBuffer, buf.Length); wbmp.AddDirtyRect(new Int32Rect(0, 0, wbmp.PixelWidth, wbmp.PixelHeight)); wbmp.Unlock(); return wbmp; }
public static void TransferBytesToWriteableBitmap(WriteableBitmap bitmap, ushort[] pixels) { bitmap.Lock(); unsafe { ushort* bPtr = (ushort*)bitmap.BackBuffer; foreach (ushort pixel in pixels) { *bPtr++ = pixel; } } bitmap.AddDirtyRect(new System.Windows.Int32Rect(0, 0, bitmap.PixelWidth, bitmap.PixelHeight)); bitmap.Unlock(); }
public Page1() { // Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. InitializeComponent(); var i = new Image(); var s = new WriteableBitmap(600, 600, 96, 96, PixelFormats.Pbgra32, null); Plasma.generatePlasma(600, 600); var shift = 0; Action Refresh = delegate { var buffer = Plasma.shiftPlasma(shift); s.Lock(); for (int j = 0; j < buffer.Length; j++) { Marshal.WriteInt32(s.BackBuffer, j * 4, unchecked((int)(buffer[j] | 0xff000000))); } s.AddDirtyRect(new Int32Rect(0, 0, 600, 600)); s.Unlock(); }; var t = new DispatcherTimer(); t.Tick += delegate { shift++; Refresh(); }; t.Interval = TimeSpan.FromMilliseconds(10); t.Start(); Refresh(); i.Source = s; this.Content = i; }
private void AddFrame(AnimatedGifEncoder encoder) { var rtb = new RenderTargetBitmap((int)this.ActualWidth, (int)this.ActualHeight, 96, 96, PixelFormats.Pbgra32); rtb.Render(this); var bitmap = new WriteableBitmap((int)this.ActualWidth, (int)this.ActualHeight, 96, 96, PixelFormats.Pbgra32, null); bitmap.FillRectangle(0, 0, bitmap.PixelWidth, bitmap.PixelWidth, Colors.Wheat); bitmap.Lock(); rtb.CopyPixels( new Int32Rect(0, 0, rtb.PixelWidth, rtb.PixelHeight), bitmap.BackBuffer, bitmap.BackBufferStride * bitmap.PixelHeight, bitmap.BackBufferStride); bitmap.AddDirtyRect(new Int32Rect(0, 0, (int)ActualWidth, (int)ActualHeight)); bitmap.Unlock(); encoder.AddFrame(bitmap); }
public Window1() { InitializeComponent(); var i = new Image(); var s = new WriteableBitmap(600, 600, 96, 96, PixelFormats.Pbgra32, null); Plasma.generatePlasma(600, 600); var shift = 0; Action Refresh = delegate { var buffer = Plasma.shiftPlasma(shift); s.Lock(); for (int j = 0; j < buffer.Length; j++) { Marshal.WriteInt32(s.BackBuffer, j * 4, unchecked((int)(buffer[j] | 0xff000000) )); } s.AddDirtyRect(new Int32Rect(0, 0, 600, 600)); s.Unlock(); }; var t = new DispatcherTimer(); t.Tick += delegate { shift++; Refresh(); }; t.Interval = TimeSpan.FromMilliseconds(10); t.Start(); Refresh(); i.Source = s; this.Content = i; }
public override void UpdateColorPlaneBitmap(WriteableBitmap bitmap, int normalComponentValue) { unsafe { bitmap.Lock(); int currentPixel = -1; byte* pStart = (byte*)(void*)bitmap.BackBuffer; for (int iRow = 0; iRow < bitmap.PixelHeight; iRow++) { for (int iCol = 0; iCol < bitmap.PixelWidth; iCol++) { currentPixel++; *(pStart + currentPixel * 3 + 0) = (byte)(iCol); //Blue *(pStart + currentPixel * 3 + 1) = (byte)(255 - iRow); //Green *(pStart + currentPixel * 3 + 2) = (byte)normalComponentValue; //red } } bitmap.AddDirtyRect(new Int32Rect(0, 0, bitmap.PixelWidth, bitmap.PixelHeight)); bitmap.Unlock(); } }
public void Draw() { if (m_wpfBitmap != null) { m_wpfBitmap.Lock(); int width = m_wpfBitmap.PixelWidth; int height = m_wpfBitmap.PixelHeight; { using (var g = Graphics.FromImage(m_gdiBitmap)) { m_draw(new Rectangle(0, 0, width, height), g); } } m_wpfBitmap.AddDirtyRect(new Int32Rect(0, 0, width, height)); m_wpfBitmap.Unlock(); } }
public void Paint(SceneMetaData sceneMeta, WriteableBitmap b) { b.Lock(); unsafe { short* pLabelRow = (short*)sceneMeta.SceneMapPtr; int nTexMapX = b.BackBufferStride; byte* pTexRow = (byte*)b.BackBuffer + sceneMeta.YOffset * nTexMapX; for (int y = 0; y < sceneMeta.YRes; y++) { short* pLabel = pLabelRow; byte* pTex = pTexRow + sceneMeta.XOffset; for (int x = 0; x < sceneMeta.XRes; x++) { //var label = sceneMeta.GetLabel((uint) x, (uint) y); var label = (*pLabel); if (label != 0) { var c = _colors[label%_colors.Length]; pTex[0] = c.B; // B pTex[1] = c.G; // G pTex[2] = c.R; // R pTex[3] = c.A; // A } else { pTex[0] = 0; // B pTex[1] = 0; // G pTex[2] = 0; // R pTex[3] = 0; // A } pLabel++; pTex += 4; } pLabelRow += sceneMeta.XRes; pTexRow += nTexMapX; } } b.AddDirtyRect(new Int32Rect(0, 0, b.PixelWidth, b.PixelHeight)); b.Unlock(); }
public MainWindow() { InitializeComponent(); AntiAlias = false; var wb = new WriteableBitmap(ViewModel.CellBoard.Width, ViewModel.CellBoard.Height, 96, 96, PixelFormats.Bgr32, null); Canvas.Source = wb; CompositionTarget.Rendering += (sender, args) => { wb.Lock(); unsafe { CellBoard.Render((uint*)wb.BackBuffer, wb.BackBufferStride, ViewModel.CellBoard.Width, ViewModel.CellBoard.Height, ViewModel.CellBoard.Cells); } wb.AddDirtyRect(new Int32Rect(0, 0, wb.PixelWidth, wb.PixelHeight)); wb.Unlock(); }; }
public static WriteableBitmap Texture2DToWriteableBitmap(this Texture2D texture) { var bmp = new WriteableBitmap(texture.Width, texture.Height, 96, 96, PixelFormats.Bgra32, null); var pixelData = new int[texture.Width * texture.Height]; texture.GetData(pixelData); //bmp.WritePixels(); bmp.Lock(); unsafe { var pixels = (int*)bmp.BackBuffer; for (int i = 0; i < pixelData.Length; i++) { pixels[i] = ColorToWindows(pixelData[i]); } } bmp.AddDirtyRect(new Int32Rect(0, 0, texture.Width, texture.Height)); bmp.Unlock(); return bmp; }
public static unsafe WriteableBitmap GetBitmap(this SharpDX.Direct3D11.Texture2D tex) { DataRectangle db; DataStream data = new DataStream(tex.Description.Height * tex.Description.Width * 4, true, true); using(var copy = tex.GetCopy()) using (var surface = copy.QueryInterface<SharpDX.DXGI.Surface>()) { db = surface.Map(SharpDX.DXGI.MapFlags.Read, out data); // can't destroy the surface now with WARP driver int w = tex.Description.Width; int h = tex.Description.Height; var wb = new WriteableBitmap(w, h, 96.0, 96.0, PixelFormats.Bgra32, null); wb.Lock(); try { uint* wbb = (uint*)wb.BackBuffer; data.Position = 0; for (int y = 0; y < h; y++) { data.Position = y * db.Pitch; for (int x = 0; x < w; x++) { var c = data.Read<uint>(); wbb[y * w + x] = c; } } } finally { wb.AddDirtyRect(new Int32Rect(0, 0, w, h)); wb.Unlock(); data.Dispose(); } return wb; } }
void Sensor_ColorFrameReady(object sender, ColorImageFrameReadyEventArgs e) { using (var frame = e.OpenColorImageFrame()) { if (frame != null) { #region Draw color frame byte[] pixels = new byte[frame.PixelDataLength]; frame.CopyPixelDataTo(pixels); WriteableBitmap bitmap = new WriteableBitmap(frame.Width, frame.Height, 96.0, 96.0, PixelFormats.Bgr32, null); bitmap.Lock(); Marshal.Copy(pixels, 0, bitmap.BackBuffer, pixels.Length); bitmap.AddDirtyRect(new Int32Rect(0, 0, frame.Width, frame.Height)); bitmap.Unlock(); camera.ImageSource = bitmap; #endregion } } }
public void DrawHeadAndHands(ref WriteableBitmap image, int id, UserGenerator userGenerator, DepthGenerator depthGenerator) { int headSize = 40; int handSize = 20; SkeletonJointPosition head = new SkeletonJointPosition(); SkeletonJointPosition leftHand = new SkeletonJointPosition(); SkeletonJointPosition rightHand = new SkeletonJointPosition(); head = userGenerator.SkeletonCapability.GetSkeletonJointPosition(id, SkeletonJoint.Head); leftHand = userGenerator.SkeletonCapability.GetSkeletonJointPosition(id, SkeletonJoint.LeftHand); rightHand = userGenerator.SkeletonCapability.GetSkeletonJointPosition(id, SkeletonJoint.RightHand); image.Lock(); var b = new Bitmap(image.PixelWidth, image.PixelHeight, image.BackBufferStride, System.Drawing.Imaging.PixelFormat.Format24bppRgb, image.BackBuffer); using (var bitmapGraphics = System.Drawing.Graphics.FromImage(b)) { bitmapGraphics.SmoothingMode = SmoothingMode.HighSpeed; bitmapGraphics.InterpolationMode = InterpolationMode.NearestNeighbor; bitmapGraphics.CompositingMode = CompositingMode.SourceCopy; bitmapGraphics.CompositingQuality = CompositingQuality.HighSpeed; int[] headCoord = ConvertCoord(head, -headSize/2); int[] leftHandCoord = ConvertCoord(leftHand, -handSize/2); int[] rightHandCoord = ConvertCoord(rightHand, -handSize/2); bitmapGraphics.DrawEllipse(Pens.BlueViolet, headCoord[0], headCoord[1], headSize, headSize); bitmapGraphics.DrawEllipse(Pens.BlueViolet, leftHandCoord[0], leftHandCoord[1], handSize, handSize); bitmapGraphics.DrawEllipse(Pens.BlueViolet, rightHandCoord[0], rightHandCoord[1], handSize, handSize); bitmapGraphics.Dispose(); } image.AddDirtyRect(new Int32Rect(0, 0, image.PixelWidth, image.PixelHeight)); image.Unlock(); }
public virtual WriteableBitmap DisplayFloatArray(ref WriteableBitmap wb, float[] d) { //NEEDS TO BE NORMALIZED BEFOREHAND wb = new WriteableBitmap((int)wb.Width, (int)wb.Height, 96, 96, PixelFormats.Bgr32, null); wb.Lock(); unsafe { for (int y = 0; y < wb.Height; y++) for (int x = 0; x < wb.Width; x++) { int pBackBuffer = (int)wb.BackBuffer; pBackBuffer += y * wb.BackBufferStride; pBackBuffer += x * 4; int value = (int)(d[(y * x) + x]); int color_data = value << 16; color_data |= value << 8; color_data |= value << 0; // Assign the color data to the pixel. *((int*)pBackBuffer) = color_data; } } try { wb.AddDirtyRect(new Int32Rect(0, 0, d.GetLength(0), d.GetLength(1))); } catch (Exception ex) { string s = ex.ToString(); } finally { wb.Unlock(); } return wb; }
public static void UpdateMinimap(World w, ref WriteableBitmap bmp) { bmp.Lock(); unsafe { int pixelCount = bmp.PixelHeight * bmp.PixelWidth; var pixels = (int*)bmp.BackBuffer; for (int i = 0; i < pixelCount; i++) { int x = i % bmp.PixelWidth; int y = i / bmp.PixelWidth; int worldX = x * Resolution; int worldY = y * Resolution; pixels[i] = XnaColorToWindowsInt(PixelMap.GetTileColor(w.Tiles[worldX, worldY], Microsoft.Xna.Framework.Color.Transparent)); } } bmp.AddDirtyRect(new Int32Rect(0, 0, bmp.PixelWidth, bmp.PixelHeight)); bmp.Unlock(); }
/** * Connect to the clientUI.colorChange event * * Update the colors in the side state list **/ private void listBox_setup(uint val, System.Drawing.Color[] colors) { // Convert colors to integer values int[] cvals = new int[colors.Length]; for (int i = 0; i < colors.Length; i++) { cvals[i] = colors[i].R << 16; cvals[i] |= colors[i].G << 8; cvals[i] |= colors[i].B; } // On the dispatcher thread, clear old entries, create a new entry // for each state. Set its color to the color for the state listBox1.Dispatcher.BeginInvoke(new Action(() => { listBox1.Items.Clear(); int i = 0; foreach (int v in cvals) { var sp = new StackPanel(); sp.Orientation = Orientation.Horizontal; var img = new Image(); img.Height = 10; img.Width = 10; var bmap = new WriteableBitmap(1, 1, 96, 96, PixelFormats.Bgr32, null); img.Source = bmap; bmap.Lock(); unsafe { int* buffer = (int*)bmap.BackBuffer; *buffer = v; } bmap.AddDirtyRect(new Int32Rect(0, 0, 1, 1)); bmap.Unlock(); sp.Children.Add(img); var label = new Label(); label.Content = "State " + i; sp.Children.Add(label); int num = i; // Add an event to bring up a color chooser and change a state's color img.MouseUp += (o, e) => { var cp = new Window3(); cp.setColor(cvals[num]); if (cp.ShowDialog() == true) { clientui.setColor((uint) num, cp.Color); } }; listBox1.Items.Add(sp); i++; } })); }
/// <summary> /// Creates a new resized WriteableBitmap. /// </summary> /// <param name="bmp">The WriteableBitmap.</param> /// <param name="width">The new desired width.</param> /// <param name="height">The new desired height.</param> /// <param name="interpolation">The interpolation method that should be used.</param> /// <returns>A new WriteableBitmap that is a resized version of the input.</returns> public static WriteableBitmap Resize(this WriteableBitmap bmp, int width, int height, Interpolation interpolation) { // Init vars int ws = bmp.PixelWidth; int hs = bmp.PixelHeight; #if SILVERLIGHT var ps = bmp.Pixels; var result = new WriteableBitmap(width, height); var pd = result.Pixels; #else bmp.Lock(); var result = new WriteableBitmap(width, height, 96.0, 96.0, PixelFormats.Bgra32, null); result.Lock(); unsafe { var ps = (int*) bmp.BackBuffer; var pd = (int*) result.BackBuffer; #endif float xs = (float) ws/width; float ys = (float) hs/height; float fracx, fracy, ifracx, ifracy, sx, sy, l0, l1; int c, x0, x1, y0, y1; byte c1a, c1r, c1g, c1b, c2a, c2r, c2g, c2b, c3a, c3r, c3g, c3b, c4a, c4r, c4g, c4b; byte a = 0, r = 0, g = 0, b = 0; // Nearest Neighbor if (interpolation == Interpolation.NearestNeighbor) { int srcIdx = 0; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { sx = x*xs; sy = y*ys; x0 = (int) sx; y0 = (int) sy; pd[srcIdx++] = ps[y0*ws + x0]; } } } // Bilinear else if (interpolation == Interpolation.Bilinear) { int srcIdx = 0; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { sx = x*xs; sy = y*ys; x0 = (int) sx; y0 = (int) sy; // Calculate coordinates of the 4 interpolation points fracx = sx - x0; fracy = sy - y0; ifracx = 1f - fracx; ifracy = 1f - fracy; x1 = x0 + 1; if (x1 >= ws) x1 = x0; y1 = y0 + 1; if (y1 >= hs) y1 = y0; // Read source color c = ps[y0*ws + x0]; c1a = (byte) (c >> 24); c1r = (byte) (c >> 16); c1g = (byte) (c >> 8); c1b = (byte) (c); c = ps[y0*ws + x1]; c2a = (byte) (c >> 24); c2r = (byte) (c >> 16); c2g = (byte) (c >> 8); c2b = (byte) (c); c = ps[y1*ws + x0]; c3a = (byte) (c >> 24); c3r = (byte) (c >> 16); c3g = (byte) (c >> 8); c3b = (byte) (c); c = ps[y1*ws + x1]; c4a = (byte) (c >> 24); c4r = (byte) (c >> 16); c4g = (byte) (c >> 8); c4b = (byte) (c); // Calculate colors // Alpha l0 = ifracx*c1a + fracx*c2a; l1 = ifracx*c3a + fracx*c4a; a = (byte) (ifracy*l0 + fracy*l1); if (a > 0) { // Red l0 = ifracx*c1r*c1a + fracx*c2r*c2a; l1 = ifracx*c3r*c3a + fracx*c4r*c4a; r = (byte) ((ifracy*l0 + fracy*l1)/a); // Green l0 = ifracx*c1g*c1a + fracx*c2g*c2a; l1 = ifracx*c3g*c3a + fracx*c4g*c4a; g = (byte) ((ifracy*l0 + fracy*l1)/a); // Blue l0 = ifracx*c1b*c1a + fracx*c2b*c2a; l1 = ifracx*c3b*c3a + fracx*c4b*c4a; b = (byte) ((ifracy*l0 + fracy*l1)/a); } // Write destination pd[srcIdx++] = (a << 24) | (r << 16) | (g << 8) | b; } } } #if !SILVERLIGHT } result.AddDirtyRect(new Int32Rect(0, 0, width, height)); result.Unlock(); bmp.Unlock(); #endif return result; }
public WriteableBitmap Decode(int offset, int chunkStartOffset) { // Dark Alliance encodes pointers as offsets from the entry in the texture entry table. // Return to arms (more sensibly) encodes pointers as offsets from the current chunk loaded from the disc. int deltaOffset = EngineVersion.DarkAlliance == _engineVersion ? offset : chunkStartOffset; int pixelWidth = DataUtil.getLEUShort(fileData, offset); int pixelHeight = DataUtil.getLEUShort(fileData, offset+2); int header10 = DataUtil.getLEInt(fileData, offset + 0x10); int compressedDataLen = DataUtil.getLEInt(fileData, offset + 0x14); int compressedDataOffset = header10 + deltaOffset; if (compressedDataOffset <= 0 || compressedDataOffset >= fileData.Length) { return null; } int palOffset = DataUtil.getLEInt(fileData, compressedDataOffset) + deltaOffset; PalEntry[] palette = PalEntry.readPalette(fileData, palOffset, 16, 16); palette = PalEntry.unswizzlePalette(palette); HuffVal[] huffVals = decodeHuff(palOffset+0xc00); int p = compressedDataOffset+4; int width = (pixelWidth + 0x0f) & ~0x0f; int height = (pixelHeight + 0x0f) & ~0x0f; WriteableBitmap image = new WriteableBitmap( width, height, 96, 96, PixelFormats.Bgr32, null); image.Lock(); while (fileData[p] != 0xFF) { int x0 = fileData[p]; int y0 = fileData[p + 1]; int x1 = fileData[p + 2]; int y1 = fileData[p + 3]; p += 4; for (int yblock = y0; yblock <= y1; ++yblock) { for (int xblock = x0; xblock <= x1; ++xblock) { int blockDataStart = DataUtil.getLEInt(fileData, p) + deltaOffset; decodeBlock(xblock, yblock, blockDataStart, palOffset + 0x400, image, palette, huffVals); p += 4; } } } // Specify the area of the bitmap that changed. image.AddDirtyRect(new Int32Rect(0, 0, width, height)); // Release the back buffer and make it available for display. image.Unlock(); return image; }
public void UpdateWriteableBitmap(WriteableBitmap bitmap) { bitmap.Lock(); unsafe { IntPtr backBuffer = bitmap.BackBuffer; int* pBackBuffer = (int*)backBuffer; PixelFormat pf = PixelFormats.Bgr32; int bytes = (pf.BitsPerPixel + 7) / 8; int[] cmap = ToIntArray(); for (int c = colorMapLength - 1; c > 0; --c) { *pBackBuffer = cmap[c]; pBackBuffer++; } } bitmap.AddDirtyRect(new Int32Rect(0,0, bitmap.PixelWidth, bitmap.PixelHeight)); bitmap.Unlock(); }
/// <summary> /// Paints on a WriteableBitmap with a stylized airbrush /// </summary> /// <param name="bmp">The bitmap to modify</param> /// <param name="from">The starting point of the stroke</param> /// <param name="to">The end point of the stroke</param> /// <param name="color">The color of the stroke</param> /// <param name="size">The size of the stroke</param> public static unsafe void Airbrush(WriteableBitmap bmp, Point from, Point to, Color color, int size) { Random r = new Random(); if (bmp == null) return; bmp.Lock(); // Create a line segment representation MyLine line = new MyLine(from, to); // Get a bounding box for the painted area BoundingBox bitmapbounds = new BoundingBox(); BoundingBox linebounds = new BoundingBox(); bitmapbounds.AddPoint(0, 0, 0); bitmapbounds.AddPoint(bmp.PixelWidth - 1, bmp.PixelHeight - 1, 0); linebounds.AddPoint((int)from.X, (int)from.Y, size + AirbrushRadiu); linebounds.AddPoint((int)to.X, (int)to.Y, size + AirbrushRadiu); linebounds.Clip(bitmapbounds); UInt32* start = (UInt32*)bmp.BackBuffer.ToPointer(); int stride = bmp.BackBufferStride / sizeof(UInt32); // Move from 'from' to 'to' along timestep intervals, with one dot painted per interval for (int i = 0; i < AirbrushDots; i++) { int x, y; line.Interpolate(i, AirbrushDots, out x, out y); int dist = r.Next() % size; double angle = r.NextDouble() * 2 * Math.PI; double dx = Math.Cos(angle) * dist; double dy = Math.Sqrt(dist * dist - dx * dx); if (angle > Math.PI) dy = -dy; int bx = x + (int)dx; int by = y + (int)dy; BoundingBox dotbounds = new BoundingBox(); dotbounds.AddPoint(bx, by, AirbrushRadiu); dotbounds.Clip(bitmapbounds); for (int k = dotbounds.Top, row = 0; k < dotbounds.Bottom; k++, y++, row++) for (int j = dotbounds.Left, col = 0; j < dotbounds.Right; j++, col++) AlphaBlended(start + stride * k + j, Color.FromArgb(AirbrushBytes[row][col], color.R, color.G, color.B)); } bmp.AddDirtyRect(new Int32Rect(linebounds.Left, linebounds.Top, linebounds.Width, linebounds.Height)); bmp.Unlock(); }
/// <summary> /// Erases paint on a WriteableBitmap /// </summary> /// <param name="bmp">The bitmap to modify</param> /// <param name="from">The starting point of the stroke</param> /// <param name="to">The end point of the stroke</param> /// <param name="size">The stroke size</param> public static unsafe void Erase(WriteableBitmap bmp, Point from, Point to, int size) { if (bmp == null) return; bmp.Lock(); // Intermediate storage of the square of the size int area = size * size; // Create a line segment representation to compare distance to MyLine line = new MyLine(from, to); // Get a bounding box for the line segment BoundingBox bitmapbounds = new BoundingBox(); BoundingBox linebounds = new BoundingBox(); bitmapbounds.AddPoint(0, 0, 0); bitmapbounds.AddPoint(bmp.PixelWidth - 1, bmp.PixelHeight - 1, 0); linebounds.AddPoint((int)from.X, (int)from.Y, size); linebounds.AddPoint((int)to.X, (int)to.Y, size); linebounds.Clip(bitmapbounds); // Get a pointer to the back buffer (we use an int pointer here, since we can safely assume a 32-bit pixel format) Int32* start = (Int32*)bmp.BackBuffer.ToPointer(); // Move the starting pixel to the x offset start += linebounds.Left; // Loop through the relevant portion of the image and figure out which pixels need to be erased for (int y = linebounds.Top; y < linebounds.Bottom; y++) { Int32* pixel = start + bmp.BackBufferStride / sizeof(Int32) * y; for (int x = linebounds.Left; x < linebounds.Right; x++) { if (line.DistanceSquared(x, y) <= area) *pixel = 0; // Move to the next pixel pixel++; } } bmp.AddDirtyRect(new Int32Rect(linebounds.Left, linebounds.Top, linebounds.Width, linebounds.Height)); bmp.Unlock(); }
/// <summary> /// Paints on a WriteableBitmap like a paintbrush /// </summary> /// <param name="bmp">The bitmap to modify</param> /// <param name="from">The starting point of the stroke</param> /// <param name="to">The end point of the stroke</param> /// <param name="previous">The point prior to the 'from' point, or null</param> /// <param name="color">The color of the brush</param> /// <param name="size">The stroke size</param> public static unsafe void Brush(WriteableBitmap bmp, Point from, Point to, Point? previous, Color color, int size) { if (bmp == null) return; bmp.Lock(); // Intermediate storage of the square of the size int area = size * size; uint flatcolor = (uint)((int)color.A << 24) + (uint)((int)color.R << 16) + (uint)((int)color.G << 8) + color.B; // Create a line segment representation to compare distance to MyLine line = new MyLine(from, to); // Get a bounding box for the line segment BoundingBox bitmapbounds = new BoundingBox(); BoundingBox linebounds = new BoundingBox(); bitmapbounds.AddPoint(0, 0, 0); bitmapbounds.AddPoint(bmp.PixelWidth - 1, bmp.PixelHeight - 1, 0); linebounds.AddPoint((int)from.X, (int)from.Y, size); linebounds.AddPoint((int)to.X, (int)to.Y, size); linebounds.Clip(bitmapbounds); // Get a pointer to the back buffer (we use an int pointer here, since we can safely assume a 32-bit pixel format) UInt32* start = (UInt32*)bmp.BackBuffer.ToPointer(); // Move the starting pixel to the x offset start += linebounds.Left; if (previous.HasValue) { MyLine previoussegment = new MyLine(previous.Value, from); // Loop through the relevant portion of the image and figure out which pixels need to be erased for (int y = linebounds.Top; y < linebounds.Bottom; y++) { UInt32* pixel = start + bmp.BackBufferStride / sizeof(UInt32) * y; for (int x = linebounds.Left; x < linebounds.Right; x++) { if (line.DistanceSquared(x, y) <= area && previoussegment.DistanceSquared(x, y) > area) { if (color.A == 255) *pixel = flatcolor; else AlphaBlended(pixel, color); } // Move to the next pixel pixel++; } } } else { // Loop through the relevant portion of the image and figure out which pixels need to be erased for (int y = linebounds.Top; y < linebounds.Bottom; y++) { UInt32* pixel = start + bmp.BackBufferStride / sizeof(UInt32) * y; for (int x = linebounds.Left; x < linebounds.Right; x++) { if (line.DistanceSquared(x, y) <= area) { if (color.A == 255) *pixel = flatcolor; else AlphaBlended(pixel, color); } // Move to the next pixel pixel++; } } } bmp.AddDirtyRect(new Int32Rect(linebounds.Left, linebounds.Top, linebounds.Width, linebounds.Height)); bmp.Unlock(); }
private static unsafe BitmapSource ToGrayScale(BitmapSource source) { const int PIXEL_SIZE = 4; int width = source.PixelWidth; int height = source.PixelHeight; var bitmap = new WriteableBitmap(source); bitmap.Lock(); var backBuffer = (byte*)bitmap.BackBuffer.ToPointer(); for (int y = 0; y < height; y++) { var row = backBuffer + (y * bitmap.BackBufferStride); for (int x = 0; x < width; x++) { var grayScale = (byte)(((row[x * PIXEL_SIZE + 1]) + (row[x * PIXEL_SIZE + 2]) + (row[x * PIXEL_SIZE + 3])) / 3); for (int i = 0; i < PIXEL_SIZE; i++) row[x * PIXEL_SIZE + i] = grayScale; } } bitmap.AddDirtyRect(new Int32Rect(0, 0, width, height)); bitmap.Unlock(); return bitmap; }
public void UpdateWorldImage(RectI area, bool isRenderedLayer = false, string renderMsg = "Render Update Complete.", WriteableBitmap img = null) { // validate area area.Rebound(_world.Header.WorldBounds); int width = area.Width; int height = area.Height; int rts = isRenderedLayer ? 8 : 1; string renderProgressMsg = isRenderedLayer ? "Rendering Textured World..." : "Rendering Pixel World..."; if (img == null) img = isRenderedLayer ? _worldImage.Rendered : _worldImage.Image; var pixels = new BytePixels(area.Size * rts, 4); var stride = img.PixelWidth * img.Format.BitsPerPixel / 8; for (int x = area.X; x <= area.Right; x++) { int dx = x - area.X; if (renderMsg != null) OnProgressChanged(this, dx, width, renderProgressMsg); for (int y = area.Y; y <= area.Bottom; y++) { int dy = y - area.Y; Tile tile = _world.Tiles[x, y]; if (tile != null) { var xy = (new PointInt32(x, y) - area.TopLeft) * rts; var bp = isRenderedLayer ? GetTexture(y, tile) : GetTextureLayer("TilePixel", y, tile); bp.PutData(pixels, xy); } } } SizeInt32 ts = new SizeInt32(rts, rts); var realArea = isRenderedLayer ? new RectI(new PointInt32(), area.Size * ts) : area; // Rendered layer starts at 0,0 img.Lock(); img.WritePixels(realArea, pixels.GetData(), stride, 0); if (!isRenderedLayer) img.AddDirtyRect(realArea); img.Unlock(); if (renderMsg != null) OnProgressChanged(this, 100, 100, renderMsg); }