public FastBitmap GetImageWithDisplacement(FastBitmap currFrame, FastBitmap nextFrame, List<Point> edgePoints) { _nBytesPerPixel = currFrame.CCount; currFrame.LockBits(); nextFrame.LockBits(); byte[] currRgbValues = currFrame.Pixels; byte[] nextRgbValues = nextFrame.Pixels; Dictionary<Point, Point> displacements = new Dictionary<Point, Point>(); foreach (Point edgePoint in edgePoints) { int edgePointPos; List<Color> pointVicinity = GetPointVicinity(edgePoint, currRgbValues, currFrame.Width, currFrame.Height, currFrame.Stride, out edgePointPos); _brief = new BRIEF((POINT_WINDOW_SIDE + 1) * (POINT_WINDOW_SIDE + 1),edgePointPos); string vicinityDescriptor = _brief.GetImageDescriptor(pointVicinity); if (pointVicinity[edgePointPos] != Color.Black) { Point nextFramePoint = FindPointDiscplacement(edgePoint, nextRgbValues, nextFrame.Width, nextFrame.Height, vicinityDescriptor, nextFrame.Stride, pointVicinity[edgePointPos]); displacements.Add(edgePoint, nextFramePoint); } else displacements.Add(edgePoint,edgePoint); } currFrame.UnlockBits(); nextFrame.UnlockBits(); DrawDisplacement(currFrame, displacements); return currFrame; }
public ThresholdForm(FastBitmap bmp) { InitializeComponent(); bmpOriginal = bmp; bmpModified = new FastBitmap((Bitmap)bmp.Bitmap.Clone()); originalPanel.Size = bmp.Size; originalPanel.Left = 0; originalPanel.Top = 0; containerPanel1.Size = new Size(300, 300); containerPanel1.Left = 10; containerPanel1.Top = 10; graphicsOriginal = originalPanel.CreateGraphics(); modifiedPanel.Size = bmp.Size; modifiedPanel.Left = 0; modifiedPanel.Top = 0; containerPanel2.Size = new Size(300, 300); containerPanel2.Left = 320; containerPanel2.Top = 10; graphicsModified = modifiedPanel.CreateGraphics(); ApplyThreshold((byte)127); }
public static unsafe Bitmap CropArea(Bitmap original, int posX, int posY, int width, int height) { Bitmap ret = new Bitmap(width, height); #if false FastBitmap retFast = new FastBitmap(ret); FastBitmap origFast = new FastBitmap(original); retFast.LockImage(); origFast.LockImage(); for (int x = posX; x < posX + width && x < original.Width; ++x) { for (int y = posY; y < posY + height && y < original.Height; ++y) { retFast.CopyFrom(x - posX, y - posY, origFast.GetPixelData(x, y)); } } retFast.UnlockImage(); origFast.UnlockImage(); #else using (Graphics g = Graphics.FromImage(ret)) { RectangleF source = new RectangleF(posX, posY, width, height); RectangleF target = new RectangleF(0, 0, width, height); g.DrawImage(original, target, source, GraphicsUnit.Pixel); } #endif return ret; }
public override void SetFontBitmap( Bitmap bmp ) { fontBmp = bmp; boxSize = fontBmp.Width / 16; fontPixels = new FastBitmap( fontBmp, true ); CalculateTextWidths(); }
private void DrawScreenPerPixel(Bitmap wallpaper, Bitmap image, Screen screen) { Point screenPosition = new Point(); Point imagePosition = new Point(); Point wallpaperPosition = new Point(); using (FastBitmap wallpaperBitmap = new FastBitmap(wallpaper)) using (FastBitmap imageBitmap = new FastBitmap(image)) { // Loop through all pixel rows for (screenPosition.Y = screen.Bounds.Y; screenPosition.Y < screen.Bounds.Bottom; screenPosition.Y++) { // Determine the vertical components of the image- and wallpaper positions imagePosition.Y = screen.BoundsInVirtualScreen.Y + (screenPosition.Y - screen.Bounds.Y); wallpaperPosition.Y = screenPosition.Y >= 0 ? screenPosition.Y : wallpaper.Height + screenPosition.Y; // Loop through all pixels in the current row for (screenPosition.X = screen.Bounds.X; screenPosition.X < screen.Bounds.Right; screenPosition.X++) { // Determine the horizontal components of the image- and wallpaper positions imagePosition.X = screen.BoundsInVirtualScreen.X + (screenPosition.X - screen.Bounds.X); wallpaperPosition.X = screenPosition.X >= 0 ? screenPosition.X : wallpaper.Width + screenPosition.X; // Assign the pixel data values at the image pixel position to the pixel at // the wallpaper pixel position (copying it over) FastBitmap.Pixel imagePixel = imageBitmap.GetPixel(imagePosition.X, imagePosition.Y); wallpaperBitmap.SetPixel(wallpaperPosition.X, wallpaperPosition.Y, imagePixel); } } } }
public Integrator(FastBitmap bitmap) { IntegralView = new int[bitmap.Width, bitmap.Height]; SquareIntegralView = new int[bitmap.Width, bitmap.Height]; for (int x = 0; x < bitmap.Width; ++x) { for (int y = 0; y < bitmap.Height; ++y) { IntegralView[x, y] = bitmap[x, y]; SquareIntegralView[x, y] = bitmap[x, y]*bitmap[x, y]; if (x-1 >=0) { IntegralView[x, y] += IntegralView[x - 1, y]; SquareIntegralView[x, y] += SquareIntegralView[x - 1, y]; } if (y-1 >= 0) { IntegralView[x, y] += IntegralView[x, y -1]; SquareIntegralView[x, y] += SquareIntegralView[x, y - 1]; } if (x - 1 >= 0 && y - 1 >=0) { IntegralView[x, y] -= IntegralView[x - 1, y - 1]; SquareIntegralView[x, y] -= SquareIntegralView[x - 1, y - 1]; } } } }
public ReturnImage GetImageWithDisplacement(FastBitmap currFrame, FastBitmap nextFrame, List<Point> edgePoints) { _nBytesPerPixel = currFrame.CCount; currFrame.LockBits(); nextFrame.LockBits(); byte[] currRgbValues = currFrame.Pixels; byte[] nextRgbValues = nextFrame.Pixels; ConcurrentDictionary<Point, Point> displacements = new ConcurrentDictionary<Point, Point>(); Parallel.ForEach(edgePoints, (edgePoint) => { int edgePointPos; List<Color> pointVicinity = GetPointVicinity(edgePoint, currRgbValues, currFrame.Width, currFrame.Height, currFrame.Stride, out edgePointPos); _brief = new BRIEF((POINT_WINDOW_SIDE + 1) * (POINT_WINDOW_SIDE + 1), edgePointPos); string vicinityDescriptor = _brief.GetImageDescriptor(pointVicinity); if (pointVicinity[edgePointPos] != Color.Black) { Point nextFramePoint = FindPointDiscplacement(edgePoint, nextRgbValues, nextFrame.Width, nextFrame.Height, vicinityDescriptor, nextFrame.Stride, pointVicinity[edgePointPos]); displacements.TryAdd(edgePoint, nextFramePoint); } else displacements.TryAdd(edgePoint, edgePoint); }); currFrame.UnlockBits(); nextFrame.UnlockBits(); Frame frame = GetFrameByChanell(currFrame, displacements); //frames.Add(); ReturnImage image = new ReturnImage(frame, currFrame); return image; }
public static int[] GrayLevelDiff(FastBitmap bmp, int dx, int dy, Point begin, Point end) { int xbegin, ybegin, xend, yend, difference; int[] lh = new int[bmp.Levels]; int[] hv = new int[bmp.Levels]; if (dx < 0) xbegin = begin.X - dx; else xbegin = begin.X; if (dx > 0) xend = end.X - dx; else xend = end.X; if (dy < 0) ybegin = begin.Y - dy; else ybegin = begin.Y; if (dy > 0) yend = end.Y - dy; else yend = end.Y; for (int y = ybegin; y < yend; y++) { for (int x = xbegin; x < xend; x++) { int color1 = bmp[x, y]; int color2 = bmp[x + dx, y + dy]; difference = Math.Abs(color1 - color2); lh[difference]++; } } for (int i = 0; i < bmp.Levels; i++) hv[i] = (int)(lh[i] / ((float)(end.X - begin.X - Math.Abs(dx)) * (float)(end.Y - begin.Y - Math.Abs(dy))) * 1000000); return hv; }
/// <summary> /// Applies the filter to the specified <paramref name="bitmap"/>. This method /// first calls <see cref="ImageReplacementFilter.GetDestinationDimensions(FastBitmap, out Int32, out Int32)" /> /// to calculate the size of the destination image. Then it calls /// <see cref="ImageReplacementFilter.ApplyFilter(FastBitmap, FastBitmap, Graphics)" /> /// which is where the overridden class implements its filter algorithm. /// </summary> /// <param name="bitmap"> /// Image to apply the <see cref="ImageReplacementFilter" /> to. /// </param> public override sealed void ApplyFilter(FastBitmap bitmap) { OnBeginApplyFilter(bitmap); // get destination dimensions int width, height; bool shouldContinue = GetDestinationDimensions(bitmap, out width, out height); if (!shouldContinue) return; DrawingVisual dv = new DrawingVisual(); ConfigureDrawingVisual(bitmap, dv); DrawingContext dc = dv.RenderOpen(); ApplyFilter(bitmap, dc, width, height); dc.Close(); RenderTargetBitmap rtb = RenderTargetBitmapUtility.CreateRenderTargetBitmap(width, height); rtb.Render(dv); FastBitmap destination = new FastBitmap(rtb); // copy metadata // TODO /*foreach (PropertyItem propertyItem in bitmap.InnerBitmap.PropertyItems) destination.InnerBitmap.SetPropertyItem(propertyItem);*/ // set new image bitmap.InnerBitmap = destination.InnerBitmap; OnEndApplyFilter(); }
public PixelReader(FastBitmap fastBitmap, Rectangle region) { if (fastBitmap == null) throw new ArgumentOutOfRangeException("fastBitmap", "must not be null"); _fastBitmap = fastBitmap; _region = region; }
/// <summary> Sets the bitmap that contains the bitmapped font characters as an atlas. </summary> public void SetFontBitmap( Bitmap bmp ) { FontBitmap = bmp; boxSize = FontBitmap.Width / 16; fontPixels = new FastBitmap( FontBitmap, true, true ); CalculateTextWidths(); }
/// <summary> /// Draw an one-pixel point of fixed color (defined by <see cref="PixelData"/>) in fixed position. /// </summary> public static void DrawPoint(FastBitmap bmp, int x, int y, PixelData color) { PixelData* addr = bmp[x, y]; addr->R = color.R; addr->G = color.G; addr->B = color.B; }
public void FastBitmapModificationsAreApplied() { List<string> files = new List<string> { ImageSources.GetFilePathByName("format-Penguins.jpg"), ImageSources.GetFilePathByName("format-Penguins.png"), }; foreach (string file in files) { Bitmap bmp = new Bitmap(file); Bitmap original = (Bitmap)bmp.Clone(); using (FastBitmap fbmp = new FastBitmap(bmp)) { // draw a pink diagonal line for (int i = 0; i < 10; i++) { fbmp.SetPixel(i, i, Color.Pink); } } AssertionHelpers.AssertImagesAreDifferent(original, bmp, "because modifying the fast bitmap should have modified the original bitmap"); } }
public Rectangle FindPupil(FastBitmap bitmap, Rectangle eye, double[,] angulars) { cube = new double[eye.Width, eye.Height, maxRad - minRad]; double maxCubeval = 0; int maxi = 0, maxj = 0, maxr = 0; Parallel.For(0, eye.Width - (int)(0.5 * eye.Width), i => //for (int i = 0; i < eye.Width; i++) { for (int j = 0; j < eye.Height - 0.5 * eye.Height; j++) { for (int r = 0; r < maxRad - minRad; r++) { cube[i, j, r] = CountCubeValue(i, j, bitmap, eye, angulars); if (maxCubeval <= cube[i, j, r]) { maxi = i; maxj = j; maxr = r; maxCubeval = cube[i, j, r]; } } } }); Rectangle result = new Rectangle(eye.X + maxi, eye.Y + maxj, minRad + maxr, minRad + maxr); return result; }
public void ApplyFilter(FastBitmap image) { const int blurRadius = 5; var map = new List<Color>[image.Width, image.Height]; for (var i = 0; i < image.Width; ++i) { for (var j = 0; j < image.Height; ++j) { for (var iInner = -blurRadius; iInner < blurRadius; ++iInner) { var x = i + iInner; if (x < 0) { continue; } if (x >= image.Width) { break; } for (var jInner = -blurRadius; jInner < blurRadius; ++jInner) { var y = j + jInner; if (y < 0) { continue; } if (y >= image.Height) { break; } var distance = Math.Sqrt((iInner*iInner) + (jInner*jInner)); if (distance > blurRadius) { continue; } if (map[i, j] == null) { map[i, j] = new List<Color>(); } map[i, j].Add(image.GetPixel(x, y)); } } } } for (var i = 0; i < image.Width; ++i) { for (var j = 0; j < image.Height; ++j) { var r = (int)map[i, j].Average(a => a.R); var g = (int)map[i, j].Average(a => a.G); var b = (int)map[i, j].Average(a => a.B); image.SetPixel(i, j, r, g, b); } } }
public FastBitmap DrawGraph(string StatName, double MaxVal) { Bitmap bitmap = new Bitmap(200, 200, System.Drawing.Imaging.PixelFormat.Format24bppRgb); FastBitmap bmp = new FastBitmap(bitmap); bmp.LockBitmap(); ProfilerValueManager statManager = GetStat(StatName); double ScaleFactor = 1 / (MaxVal / 200); //We multiply by this so that the graph uses the full space double[] Stats = statManager.GetInfos(); for (int x = 200; x > 0; x--) { for (int y = 200; y > 0; y--) { //Note: we do 200-y to flip the graph on the Y axis if (IsInGraphBar(x, y, Stats, ScaleFactor)) bmp.SetPixel(x, 200 - y, BarColor); else { //Check whether the line needs drawn if (DrawLine(y, ScaleFactor)) bmp.SetPixel(x, 200 - y, LineColor); else bmp.SetPixel(x, 200 - y, BackgroundColor); } } } bmp.UnlockBitmap(); return bmp; }
public FastBitmap(FastBitmap bmp, Rectangle src) { if (bmp == null) throw new ArgumentNullException("bitmap"); bitmap = new Bitmap(src.Width, src.Height, PixelFormat.Format8bppIndexed); bitmap.SetResolution(bitmap.HorizontalResolution, bitmap.VerticalResolution); levels = bmp.Levels; bitmap.Palette = bmp.Palette; Lock(); unsafe { if (bmp != null) { Byte* pPixel = (Byte*)bitmapData.Scan0; for (int y = 0; y < bitmap.Height; y++) { for (int x = 0; x < bitmap.Width; x++) { pPixel[x] = bmp[x + src.X, y + src.Y]; } pPixel += bitmapData.Stride; } } } }
private Bitmap RenderFrame(LinePairCollection lines, FastBitmap startImage, FastBitmap endImage, double percent) { var forwardsAndBackwards = InterpolateLines(lines, percent); using (Bitmap forward = ComputePreimage( startImage, forwardsAndBackwards.Item1)) using (Bitmap backward = ComputePreimage( endImage, forwardsAndBackwards.Item2)) return BlendImages(forward, backward, 1 - percent); }
public ImagePreview(String path) { InitializeComponent(); this.path = path; StreamReader reader = new StreamReader(path); Bitmap bmpTemp = (Bitmap)Bitmap.FromStream(reader.BaseStream); Bitmap bmpTemp2 = new Bitmap(bmpTemp.Size.Width, bmpTemp.Size.Height); bmpTemp2.SetResolution(bmpTemp.HorizontalResolution, bmpTemp.VerticalResolution); Graphics gr = Graphics.FromImage(bmpTemp2); gr.DrawImage(bmpTemp, new Point()); bmpTemp.Dispose(); reader.Close(); bmp = new FastBitmap(bmpTemp2); bmp.Bitmap.SetResolution(96, 96); Text = path; ClientSize = bmp.Size; graphicsPanel.Left = 0; graphicsPanel.Top = 0; graphicsPanel.Size = bmp.Size; graphics = this.graphicsPanel.CreateGraphics(); }
static unsafe void CopyScaledPixels( FastBitmap src, FastBitmap dst, Size scale, Rectangle srcRect, Rectangle dstRect, byte rgbScale) { int srcWidth = srcRect.Width, dstWidth = dstRect.Width; int srcHeight = srcRect.Height, dstHeight = dstRect.Height; int srcX = srcRect.X, dstX = dstRect.X; int srcY = srcRect.Y, dstY = dstRect.Y; int scaleWidth = scale.Width, scaleHeight = scale.Height; for( int yy = 0; yy < dstHeight; yy++ ) { int scaledY = yy * srcHeight / scaleHeight; int* srcRow = src.GetRowPtr( srcY + scaledY ); int* dstRow = dst.GetRowPtr( dstY + yy ); for( int xx = 0; xx < dstWidth; xx++ ) { int scaledX = xx * srcWidth / scaleWidth; int pixel = srcRow[srcX + scaledX]; int col = pixel & ~0xFFFFFF; // keep a but clear rgb col |= ((pixel & 0xFF) * rgbScale / 255); col |= (((pixel >> 8) & 0xFF) * rgbScale / 255) << 8; col |= (((pixel >> 16) & 0xFF) * rgbScale / 255) << 16; dstRow[dstX + xx] = col; } } }
public void EditAllPixelsEditAllPixel2() { FastBitmap img = new FastBitmap("../../image/1.jpg"); img.EditAllPixels(threshold, (Object) 240); Assert.IsTrue(img.ToBitmap().GetPixel(0, 0) == Color.FromArgb(255,0,0,0)); Assert.IsTrue(img.ToBitmap().GetPixel(img.Width - 1, img.Height - 1) == Color.FromArgb(255, 255, 255, 255)); }
public void UpdateState( TerrainAtlas2D atlas2D ) { int maxVerSize = Math.Min( 4096, graphics.MaxTextureDimensions ); int verElements = maxVerSize / atlas2D.elementSize; int totalElements = TerrainAtlas2D.RowsCount * TerrainAtlas2D.ElementsPerRow; int elemSize = atlas2D.elementSize; int atlasesCount = Utils.CeilDiv( totalElements, verElements ); usedElementsPerAtlas1D = Math.Min( verElements, totalElements ); int atlas1DHeight = Utils.NextPowerOf2( usedElementsPerAtlas1D * atlas2D.elementSize ); int index = 0; TexIds = new int[atlasesCount]; Utils.LogDebug( "Loaded new atlas: {0} bmps, {1} per bmp", atlasesCount, usedElementsPerAtlas1D ); using( FastBitmap atlas = new FastBitmap( atlas2D.AtlasBitmap, true ) ) { for( int i = 0; i < TexIds.Length; i++ ) { Bitmap atlas1d = new Bitmap( atlas2D.elementSize, atlas1DHeight ); using( FastBitmap dst = new FastBitmap( atlas1d, true ) ) { for( int y_1D = 0; y_1D < usedElementsPerAtlas1D; y_1D++ ) { int x = index & 0x0F; int y = index >> 4; FastBitmap.MovePortion( x * elemSize, y * elemSize, 0, y_1D * elemSize, atlas, dst, elemSize ); index++; } TexIds[i] = graphics.CreateTexture( dst ); } atlas1d.Dispose(); } } elementsPerBitmap = atlas1DHeight / atlas2D.elementSize; invElementSize = 1f / elementsPerBitmap; }
protected override Effect GetEffect(FastBitmap source) { return new BrightnessAdjustmentEffect { Level = this.Level/100.0 }; }
public static unsafe Color AverageColor(Bitmap img) { #if true if (img.Width > avgColorPxSize && img.Height > avgColorPxSize) { img = Resize(img, avgColorPxSize, avgColorPxSize); } #endif double r = 0, g = 0, b = 0; FastBitmap fast = new FastBitmap(img); fast.LockImage(); FastBitmap.PixelData* px = fast.GetPixelData(0, 0); for (int i = 0; i < img.Width * img.Height; ++i) { r += px->red; g += px->green; b += px->blue; ++px; } fast.UnlockImage(); r /= (img.Width * img.Height); g /= (img.Width * img.Height); b /= (img.Width * img.Height); return Color.FromArgb((int)r, (int)g, (int)b); }
/// <summary>Create the morphed images and video.</summary> public void Render(IImageWriter imageWriter, LinePairCollection lines, Bitmap startImageBmp, Bitmap endImageBmp) { _curFrame = 0; double percentagePerFrame = 1.0 / (_options.NumberOfOutputFrames - 1); using (Bitmap clonedStart = Utilities.CreateNewBitmapFrom(startImageBmp)) using (Bitmap clonedEnd = Utilities.CreateNewBitmapFrom(endImageBmp)) { // Write out the starting picture imageWriter.AddFrame(clonedStart); _curFrame = 1; UpdateProgressChanged(); using (FastBitmap startImage = new FastBitmap(startImageBmp)) using (FastBitmap endImage = new FastBitmap(endImageBmp)) { for (int i = 1; i < _options.NumberOfOutputFrames - 1; i++) { _cancellationToken.ThrowIfCancellationRequested(); using (Bitmap frame = RenderFrame(lines, startImage, endImage, percentagePerFrame * i)) { imageWriter.AddFrame(frame); } _curFrame++; UpdateProgressChanged(); } } imageWriter.AddFrame(clonedEnd); _curFrame++; UpdateProgressChanged(); } }
public override void Draw( IWindowInfo info, Bitmap framebuffer ) { using( FastBitmap bmp = new FastBitmap( framebuffer, true ) ) { IntPtr scan0 = bmp.Scan0; int size = bmp.Width * bmp.Height * 4; IntPtr colorSpace = OSX.API.CGColorSpaceCreateDeviceRGB(); IntPtr provider = OSX.API.CGDataProviderCreateWithData( IntPtr.Zero, scan0, size, IntPtr.Zero ); const uint flags = 4 | (2 << 12); IntPtr image = OSX.API.CGImageCreate( bmp.Width, bmp.Height, 8, 8 * 4, bmp.Stride, colorSpace, flags, provider, IntPtr.Zero, 0, 0 ); IntPtr context = IntPtr.Zero; OSStatus err = OSX.API.QDBeginCGContext( windowPort, ref context ); OSX.API.CheckReturn( err ); OSX.HIRect rect = new OSX.HIRect(); rect.Origin.X = 0; rect.Origin.Y = 0; rect.Size.X = bmp.Width; rect.Size.Y = bmp.Height; OSX.API.CGContextDrawImage( context, rect, image ); OSX.API.CGContextSynchronize( context ); err = OSX.API.QDEndCGContext( windowPort, ref context ); OSX.API.CheckReturn( err ); OSX.API.CGImageRelease( image ); OSX.API.CGDataProviderRelease( provider ); OSX.API.CGColorSpaceRelease( colorSpace ); } }
public IBitmap ApplyArea(IArea area) { //todo: performance can be improved by only creating a bitmap the size of the area, and not the entire background. //This will require to change the rendering as well to offset the location byte zero = (byte)0; Bitmap output = new Bitmap(Width, Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); using (FastBitmap inBmp = new FastBitmap (_bitmap, ImageLockMode.ReadOnly)) { using (FastBitmap outBmp = new FastBitmap (output, ImageLockMode.WriteOnly, true)) { for (int y = 0; y < Height; y++) { int bitmapY = Height - y - 1; for (int x = 0; x < Width; x++) { System.Drawing.Color color = inBmp.GetPixel(x, bitmapY); byte alpha = area.IsInArea(new AGS.API.PointF(x, y)) ? color.A : zero; outBmp.SetPixel(x, bitmapY, System.Drawing.Color.FromArgb(alpha, color)); } } } } return new DesktopBitmap(output, _graphics); }
public static unsafe void DrawScaledPixels( FastBitmap src, FastBitmap dst, Size scale, Rectangle srcRect, Rectangle dstRect, byte scaleA, byte scaleB) { int srcWidth = srcRect.Width, dstWidth = dstRect.Width; int srcHeight = srcRect.Height, dstHeight = dstRect.Height; int srcX = srcRect.X, dstX = dstRect.X; int srcY = srcRect.Y, dstY = dstRect.Y; int scaleWidth = scale.Width, scaleHeight = scale.Height; for( int yy = 0; yy < dstHeight; yy++ ) { int scaledY = (yy + dstY) * srcHeight / scaleHeight; int* srcRow = src.GetRowPtr( srcY + (scaledY % srcHeight) ); int* dstRow = dst.GetRowPtr( dstY + yy ); byte rgbScale = (byte)Utils.Lerp( scaleA, scaleB, (float)yy / dstHeight ); for( int xx = 0; xx < dstWidth; xx++ ) { int scaledX = (xx + dstX) * srcWidth / scaleWidth; int pixel = srcRow[srcX + (scaledX % srcWidth)]; int col = pixel & ~0xFFFFFF; // keep a, but clear rgb col |= ((pixel & 0xFF) * rgbScale / 255); col |= (((pixel >> 8) & 0xFF) * rgbScale / 255) << 8; col |= (((pixel >> 16) & 0xFF) * rgbScale / 255) << 16; dstRow[dstX + xx] = col; } } }
public static Color AverageColor(Bitmap bitmap) { FastBitmap fbm = new FastBitmap(bitmap); int width = bitmap.Width, height = bitmap.Height; int r = 0, g = 0, b = 0, total = width * height; fbm.LockImage(); Color c = fbm.GetPixel(0, 0); r += c.R; g += c.G; b += c.B; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { c = fbm.GetPixel(x, y); r += c.R; g += c.G; b += c.B; } } fbm.UnlockImage(); r /= total; r = (r / 16) * 16; g /= total; g = (g / 16) * 16; b /= total; b = (b / 16) * 16; return Color.FromArgb(r, g, b); }
private QuickDraw(Bitmap bitmap) { fast = new FastBitmap(bitmap); width = bitmap.Width; height = bitmap.Height; format = bitmap.PixelFormat; Bpp = (Image.GetPixelFormatSize(bitmap.PixelFormat) / 8); ; }
void TextureChanged(string name, byte[] data) { if (Utils.CaselessEq(name, "animations.png")) { animBmp = Platform.ReadBmp(game.Drawer2D, data); animsBuffer = new FastBitmap(animBmp, true, true); } else if (Utils.CaselessEq(name, "animations.txt")) { MemoryStream stream = new MemoryStream(data); StreamReader reader = new StreamReader(stream, false); ReadAnimationsDescription(reader); } else if (Utils.CaselessEq(name, "uselavaanim")) { useLavaAnim = true; } else if (Utils.CaselessEq(name, "usewateranim")) { useWaterAnim = true; } }
protected override void DrawCore(DrawArgs args) { if (_currentMap == null) { return; } // 绘制地图 args.FastBitmap.Lock(); args.FastBitmap.CopyRegion(_currentMap.Bitmap, _currentRectangle, new Rectangle(0, 0, args.Width, args.Height)); args.FastBitmap.Unlock(); //绘制遮罩层 FastBitmap fastBitmap = new FastBitmap(args.CurrentCanvas.Normal); fastBitmap.Lock(); fastBitmap.CopyRegion(_currentMap.MaskBitmap, _currentRectangle, new Rectangle(0, 0, args.Width, args.Height)); fastBitmap.Unlock(); //设置世界坐标 args.WorldPoint = new Point(_currentRectangle.X, _currentRectangle.Y); }
public static FastBitmap Manual(FastBitmap fb, int setThreshold) { Bitmap retVal = new Bitmap(fb.bmp.Width, fb.bmp.Height); FastBitmap fastRetVal = new FastBitmap(retVal); for (int x = 0; x < retVal.Width; x++) { for (int y = 0; y < retVal.Height; y++) { if (fb.GetPixel(x, y).R > setThreshold) { fastRetVal.SetPixel(x, y, Color.White); } else { fastRetVal.SetPixel(x, y, Color.Black); } } } return(fastRetVal); }
protected override void CreateImage() { string filename = FileSourceHelper.ResolveFileName(SourceFileName); MediaPlayer mediaPlayer = new MediaPlayer { ScrubbingEnabled = true }; object monitorObject = new object(); mediaPlayer.MediaOpened += (sender, e) => Monitor.Exit(monitorObject); Monitor.Enter(monitorObject); mediaPlayer.Open(new Uri(filename)); Monitor.Wait(monitorObject, 1000); int width = mediaPlayer.NaturalVideoWidth; int height = mediaPlayer.NaturalVideoHeight; // Seek to specified time. mediaPlayer.BufferingEnded += (sender, e) => Monitor.Exit(monitorObject); Monitor.Enter(monitorObject); mediaPlayer.Position = SnapshotTime; Monitor.Wait(monitorObject, 1000); DrawingVisual dv = new DrawingVisual(); DrawingContext dc = dv.RenderOpen(); dc.DrawVideo(mediaPlayer, new System.Windows.Rect(0, 0, width, height)); dc.Close(); RenderTargetBitmap rtb = RenderTargetBitmapUtility.CreateRenderTargetBitmap(width, height); rtb.Render(dv); Bitmap = new FastBitmap(rtb); mediaPlayer.Close(); }
private Byte GetBumpMapPixel(FastBitmap bmp, Int32 x, Int32 y) { if (x < 0) { x = 0; } if (x > _bitmap.Width - 1) { x = _bitmap.Width - 1; } if (y < 0) { y = 0; } if (y > _bitmap.Height - 1) { y = _bitmap.Height - 1; } return(bmp.GetIntensity(x, y)); }
/// <summary> /// Generates an image that represents the sequential sprite strip from the specified animation. /// If the animation contains no frames, an empty 1x1 image is returned /// </summary> /// <param name="animation">The animation to generate the sprite strip image from</param> /// <returns>An image that represents the sequential sprite strip from the specified animation</returns> public Image GenerateSpriteStrip(Animation animation) { // If the frame count is 0, return an empty 1x1 image if (animation.FrameCount == 0) { return(new Bitmap(1, 1, PixelFormat.Format32bppArgb)); } // Create the image var stripBitmap = new Bitmap(animation.Width * animation.FrameCount, animation.Height); // Copy the frames into the strip bitmap now foreach (var frame in animation.Frames) { using (var composed = frame.GetComposedBitmap()) { FastBitmap.CopyRegion(composed, stripBitmap, new Rectangle(Point.Empty, frame.Size), new Rectangle(new Point(frame.Index * frame.Width, 0), frame.Size)); } } return(stripBitmap); }
/// <inheritdoc cref="FractalBase.DrawInner"/> protected override void DrawInner(FastBitmap fractal) { Enumerable.Range(0, Width * Height).AsParallel().ForAll(xy => { Complex C, newC, oldC; int x = xy % Width, y = xy / Width, i = 0; C = new Complex((x - Width / 2) / (0.5 * Zoom * Width) + MoveX, (y - Height / 2) / (0.5 * Zoom * Height) + MoveY); newC = new Complex(0, 0); for (; i < Iterations; i++) { oldC = newC; newC = new Complex(oldC.Real * oldC.Real - oldC.Imaginary * oldC.Imaginary + C.Real, 2 * oldC.Real * oldC.Imaginary + C.Imaginary); if ((newC.Real * newC.Real + newC.Imaginary * newC.Imaginary) > 4) { break; } } fractal.SetPixel(x, y, Colors[i % 256]); }); }
void TextureChanged(object sender, TextureEventArgs e) { if (e.Name == "animations.png" || e.Name == "animation.png") { animBmp = Platform.ReadBmp32Bpp(game.Drawer2D, e.Data); animsBuffer = new FastBitmap(animBmp, true, true); } else if (e.Name == "animations.txt" || e.Name == "animation.txt") { MemoryStream stream = new MemoryStream(e.Data); StreamReader reader = new StreamReader(stream); ReadAnimationsDescription(reader); } else if (e.Name == "uselavaanim") { useLavaAnim = true; } else if (e.Name == "usewateranim") { useWaterAnim = true; } }
public void TestSlicedDestinationCopyRegion() { // Have a copy operation that goes: // // -src--- // -dest-|-----|------ // | |xxxxx| | // | |xxxxx| | // ------|-----|------ // ------- // var canvasBitmap = new Bitmap(128, 32); var copyBitmap = GenerateRainbowBitmap(32, 64); var sourceRectangle = new Rectangle(0, 0, 32, 64); var targetRectangle = new Rectangle(48, -16, 32, 64); FastBitmap.CopyRegion(copyBitmap, canvasBitmap, sourceRectangle, targetRectangle); BitmapSnapshot.Snapshot(canvasBitmap, TestContext); }
public static Dictionary <string, Bitmap> SplitTexture(PsbDictionary tex, PsbSpec spec) { var icon = (PsbDictionary)tex["icon"]; var texture = (PsbDictionary)tex["texture"]; //var mipmap = (PsbDictionary)texture["mipMap"]; //TODO: Mipmap? Dictionary <string, Bitmap> textures = new Dictionary <string, Bitmap>(icon.Count); var md = PsbResCollector.GenerateMotionResMetadata(texture, (PsbResource)texture["pixel"]); md.Spec = spec; //Important Bitmap bmp = md.ToImage(); foreach (var iconPair in icon) { var info = (PsbDictionary)iconPair.Value; var width = (int)(PsbNumber)info["width"]; var height = (int)(PsbNumber)info["height"]; var top = (int)(PsbNumber)info["top"]; var left = (int)(PsbNumber)info["left"]; Bitmap b = new Bitmap(width, height, PixelFormat.Format32bppArgb); #if USE_FASTBITMAP using (FastBitmap f = b.FastLock()) { f.CopyRegion(bmp, new Rectangle(left, top, width, height), new Rectangle(0, 0, b.Width, b.Height)); } #else Graphics g = Graphics.FromImage(b); //g.InterpolationMode = InterpolationMode.NearestNeighbor; //g.PixelOffsetMode = PixelOffsetMode.Half; g.DrawImage(bmp, new Rectangle(0, 0, b.Width, b.Height), new Rectangle(left, top, width, height), GraphicsUnit.Pixel); g.Dispose(); #endif textures.Add(iconPair.Key, b); } bmp.Dispose(); return(textures); }
public void AddCustomIcon(string fileName) { bool found = false; if (!string.IsNullOrEmpty(fileName)) { if (FileOperations.FileExists(fileName)) { found = true; } } if (found) { Bitmap tmp = FastBitmap.FromFile(fileName); icons.Add(BitmapPainter.ResizeBitmap(tmp, 32, 32, true)); } else { icons.Add(BitmapPainter.ResizeBitmap(NativeThemeManager.Load("SmallKrento.png"), 32, 32, true)); } }
public void TestSlicedDestinationCopyRegion() { // Have a copy operation that goes: // // -src--- // -dest-|-----|------ // | |xxxxx| | // | |xxxxx| | // ------|-----|------ // ------- // Bitmap canvasBitmap = new Bitmap(128, 32); Bitmap copyBitmap = GenerateRandomBitmap(32, 64); Rectangle sourceRectangle = new Rectangle(0, 0, 32, 64); Rectangle targetRectangle = new Rectangle(32, -16, 32, 64); FastBitmap.CopyRegion(copyBitmap, canvasBitmap, sourceRectangle, targetRectangle); AssertCopyRegionEquals(canvasBitmap, copyBitmap, targetRectangle, sourceRectangle); }
public void MakeBackground() { if (Framebuffer == null || (Framebuffer.Width != Width || Framebuffer.Height != Height)) { if (Framebuffer != null) { Framebuffer.Dispose(); } Framebuffer = new Bitmap(Width, Height); } if (ClassicMode) { using (FastBitmap dst = new FastBitmap(Framebuffer, true)) { ClearTile(0, 0, Width, 48, elemSize, 128, 64, dst); ClearTile(0, 48, Width, Height - 48, 0, 96, 96, dst); } } else { ClearArea(0, 0, Width, Height); } using (IDrawer2D drawer = Drawer) { drawer.SetBitmap(Framebuffer); drawer.UseBitmappedChat = useBitmappedFont; DrawTextArgs args = new DrawTextArgs("&eClassical&fSharp", logoFont, false); Size size = drawer.MeasureChatSize(ref args); int xStart = Width / 2 - size.Width / 2; args.Text = "&0Classical&0Sharp"; drawer.DrawChatText(ref args, xStart + 4, 8 + 4); args.Text = "&eClassical&fSharp"; drawer.DrawChatText(ref args, xStart, 8); drawer.UseBitmappedChat = false; } Dirty = true; }
public void CropFilter_UseXYWidthHeight_CalculatedCorrectly() { FastBitmap bitmap = new FastBitmap("Resources/Tulips.png", UriKind.Relative); CropFilter cropFilter = new CropFilter(); cropFilter.X = 30; cropFilter.Y = 30; cropFilter.Width = 200; cropFilter.Height = 200; cropFilter.ApplyFilter(null, bitmap); Assert.AreEqual(200, bitmap.Width); Assert.AreEqual(200, bitmap.Height); bitmap.Save("TulipsCropped200x200.png"); FastBitmap expectedBitmap = new FastBitmap("Resources/TulipsCropped200x200.png", UriKind.Relative); FastBitmapTestUtility.AssertEqual(expectedBitmap, bitmap); }
private static Bitmap ReadIndexed(SwfReader reader, int width, int height, bool alpha) { //BitmapColorTableSize - this value is one less than the actual number of colors in the //color table, allowing for up to 256 colors. int palSize = reader.ReadUInt8() + 1; reader = reader.Unzip(); var pf = GetIndexedPixelFormat(palSize); var bmp = new Bitmap(width, height, pf); var pal = bmp.Palette.Entries; for (int i = 0; i < palSize; ++i) { pal[i] = alpha ? reader.ReadRGBA() : reader.ReadRGB(); } //NOTE: Row widths in the pixel data fields of these structures must be rounded up to the next //32-bit word boundary. For example, an 8-bit image that is 253 pixels wide must be //padded out to 256 bytes per line. To determine the appropriate padding, make sure to //take into account the actual size of the individual pixel structures; 15-bit pixels occupy 2 //bytes and 24-bit pixels occupy 4 bytes (see PIX15 and PIX24). using (var fbmp = new FastBitmap(bmp)) { for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { int i = reader.ReadUInt8(); Debug.Assert(i < palSize); fbmp.SetIndex(x, y, i); } reader.Round32(); } } return(bmp); }
/// <summary> /// Задает изображения для теста (по кругу). /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button4_Click(object sender, EventArgs e) { Bitmap bitmapRGB, bitmapTEMP, bitmapREAL; if (iterator == 1) { bitmapRGB = Resource1.TestRGB_1; bitmapTEMP = Resource1.TestTEMP_1; bitmapREAL = Resource1.TestReal_1; iterator++; } else if (iterator == 2) { bitmapRGB = Resource1.TestRGB_2; bitmapTEMP = Resource1.TestTEMP_2; bitmapREAL = Resource1.TestReal_2; iterator++; } else { bitmapRGB = Resource1.TestRGB_3; bitmapTEMP = Resource1.TestTEMP_3; bitmapREAL = Resource1.TestReal_3; iterator = 1; } imgRGB = new FastBitmap(bitmapRGB); imgTEMP = new FastBitmap(bitmapTEMP); imgGray = imgRGB.Clone(); imgGray.ToGray(); imgTEMPGray = imgTEMP.Clone(); imgTEMPGray.ToGray(); imgReal = new FastBitmap(bitmapREAL); pictureRGB.Image = imgRGB.Bitmap; pictureTEMP.Image = imgTEMP.Bitmap; }
public void ResizeSIMD2(FastBitmap rtnImage) { float scaleX = (float)this.width / rtnImage.width; float scaleY = (float)this.height / rtnImage.height; if (rtnImage.width % 4 == 0) { Parallel.For(0, rtnImage.height, (y) => { var basePos = (uint *)(rtnImage._ptr + (rtnImage._stride * y)); var rtnPos = (uint *)(this._ptr + (this._stride * (int)(y * scaleY))); Vector128 <float> indexf = Vector128.Create(0.0f, 1, 2, 3); Vector128 <float> iterf = Vector128.Create(4f, 4, 4, 4); Vector128 <float> scalef = Vector128.Create(scaleX, scaleX, scaleX, scaleX); for (int x = 0; x < rtnImage.width; x += 4) { Vector128 <int> index = Avx.ConvertToVector128Int32WithTruncation(Avx.Multiply(indexf, scalef)); Avx.Store(basePos, Avx2.GatherVector128(rtnPos, index, 4)); indexf = Avx.Add(indexf, iterf); basePos += 4; } }); } else { Parallel.For(0, height, (y) => { var basePos = (uint *)(rtnImage._ptr + (rtnImage._stride * y)); var rtnPos = (uint *)(this._ptr + (this._stride * (int)(y * scaleY))); for (int x = 0; x < width; x += 4) { *(uint *)(basePos + x) = *(uint *)(rtnPos + ((int)(x * scaleX))); } }); } }
/// <summary> /// Adjust the gamma (intensity of the light) component of the given image. /// </summary> /// <param name="source"> /// The <see cref="Image"/> source to adjust. /// </param> /// <param name="value"> /// The value to adjust the gamma by (typically between .2 and 5). /// </param> /// <returns> /// The <see cref="Bitmap"/> with the gamma adjusted. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if the value falls outside the acceptable range. /// </exception> public static Bitmap Gamma(Image source, float value) { if (value > 5 || value < .1) { throw new ArgumentOutOfRangeException(nameof(value), "Value should be between .1 and 5."); } var ramp = new byte[256]; for (var x = 0; x < 256; ++x) { var val = ((255.0 * Math.Pow(x / 255.0, value)) + 0.5).ToByte(); ramp[x] = val; } var width = source.Width; var height = source.Height; using (var bitmap = new FastBitmap(source)) { Parallel.For( 0, height, y => { for (var x = 0; x < width; x++) { // ReSharper disable once AccessToDisposedClosure var composite = bitmap.GetPixel(x, y); var linear = Color.FromArgb(composite.A, ramp[composite.R], ramp[composite.G], ramp[composite.B]); // ReSharper disable once AccessToDisposedClosure bitmap.SetPixel(x, y, linear); } }); } return((Bitmap)source); }
/// <summary> /// Applies the filter to the specified <paramref name="bitmap"/>. This method /// first calls <see cref="ImageReplacementFilter.GetDestinationDimensions(FastBitmap, out Int32, out Int32)" /> /// to calculate the size of the destination image. Then it calls /// <see cref="ImageReplacementFilter.ApplyFilter(FastBitmap, DrawingContext, int, int)" /> /// which is where the overridden class implements its filter algorithm. /// </summary> /// <param name="bitmap"> /// Image to apply the <see cref="ImageReplacementFilter" /> to. /// </param> public sealed override void ApplyFilter(FastBitmap bitmap) { OnBeginApplyFilter(bitmap); // get destination dimensions int width, height; bool shouldContinue = GetDestinationDimensions(bitmap, out width, out height); if (!shouldContinue) { return; } DrawingVisual dv = new DrawingVisual(); ConfigureDrawingVisual(bitmap, dv); DrawingContext dc = dv.RenderOpen(); ApplyFilter(bitmap, dc, width, height); dc.Close(); RenderTargetBitmap rtb = RenderTargetBitmapUtility.CreateRenderTargetBitmap(width, height); rtb.Render(dv); FastBitmap destination = new FastBitmap(rtb); // copy metadata // TODO /*foreach (PropertyItem propertyItem in bitmap.InnerBitmap.PropertyItems) * destination.InnerBitmap.SetPropertyItem(propertyItem);*/ // set new image bitmap.InnerBitmap = destination.InnerBitmap; OnEndApplyFilter(); }
public void TestUndoOperation() { // Create the objects Bitmap target = new Bitmap(64, 64); FastBitmap.ClearBitmap(target, Color.Transparent); byte[] originalHash = GetHashForBitmap(target); // Create the test subjects PlottingPaintUndoGenerator generator = new PlottingPaintUndoGenerator(target, "Pencil"); PencilPaintOperation operation = new PencilPaintOperation(target) { Color = Color.Black, Notifier = generator }; operation.StartOpertaion(); operation.MoveTo(5, 5); operation.DrawTo(10, 10); operation.DrawTo(15, 17); operation.DrawTo(20, 25); operation.DrawTo(25, 37); operation.DrawTo(5, 5); operation.FinishOperation(); // Test the undo task target Assert.AreEqual(generator.UndoTask.TargetBitmap, target, "The target for a bitmap undo should be the bitmap that was operated upon"); // Undo the task generator.UndoTask.Undo(); byte[] afterUndoHash = GetHashForBitmap(target); RegisterResultBitmap(target, "PencilOperation_AfterUndo"); Assert.IsTrue(originalHash.SequenceEqual(afterUndoHash), "After undoing a paint operation's task, its pixels must return to their original state before the operation was applied"); }
public Bitmap GetImageTransparentPal(int index) { if (ImagesPal == null || ImagesPal.Count <= index) { return(null); } if (IsDrawnPal(index) == false) { if (DrawPalImage(index) == false) { throw new Exception("Failed to draw pal-image on index #" + index); } } var img = ImagesPal[index].Image.Clone() as Bitmap; if (img == null) { throw new Exception("Invalid pal image on index #" + index); } var bg = Palette[0]; var fb = new FastBitmap(img); fb.LockImage(); for (var x = 0; x < img.Width; x++) { for (var y = 0; y < img.Height; y++) { if (fb.GetPixel(x, y) == bg) { fb.SetPixel(x, y, Color.Transparent); } } } fb.UnlockImage(); return(img); }
protected override void ApplyFilter(FastBitmap source, DrawingContext dc, int width, int height) { GradientStopCollection gradientStops = new GradientStopCollection(); gradientStops.Add(new GradientStop(Color.FromArgb(0, 0, 0, 0), 0)); gradientStops.Add(new GradientStop(Color.FromArgb(0, 0, 0, 0), 0.5)); gradientStops.Add(new GradientStop(Color.FromArgb(180, 0, 0, 0), 1.3)); gradientStops.Add(new GradientStop(Color.FromArgb(230, 0, 0, 0), 1.7)); RadialGradientBrush brush = new RadialGradientBrush(gradientStops) { GradientOrigin = new Point(0.5, 0.5), Center = new Point(0.5, 0.45), RadiusX = 0.5, RadiusY = 0.5 }; dc.DrawImage(source.InnerBitmap, new Rect(0, 0, width, height)); dc.PushOpacityMask(brush); dc.DrawRectangle(new SolidColorBrush(Colors.Black), null, new Rect(0, 0, width, height)); dc.Pop(); }
public Bitmap DrawImage(Color[] colors) { if (Width < 1 || Height < 1) { return(null); } var image = new Bitmap(Width, Height); var fastBmp = new FastBitmap(image); fastBmp.LockImage(); for (int y = 0, i = 0; y < Height; y++) { for (var x = 0; x < Width; x++) { fastBmp.SetPixel(x, y, colors[(int)Cells[i++].Type]); } } fastBmp.UnlockImage(); return(image); }
public override void Redraw(IDrawer2D drawer) { if (Window.Minimised || !Visible) { return; } Rectangle rect = new Rectangle(X, Y, Width, Height / 2); using (FastBitmap bmp = Window.LockBits()) { Gradient.Vertical(bmp, rect, boxTop, boxBottom); rect.Y += rect.Height; Gradient.Vertical(bmp, rect, boxBottom, boxTop); if (Value) { const int size = 12; int x = X + Width / 2 - size / 2; int y = Y + Height / 2 - size / 2; BitmapDrawer.DrawIndexed(indices, palette, size, x, y, bmp); } } drawer.DrawRectBounds(FastColour.Black, 1, X, Y, Width - 1, Height - 1); }
unsafe void ApplyAnimation(AnimationData data) { data.Tick--; if (data.Tick >= 0) { return; } data.CurrentState++; data.CurrentState %= data.StatesCount; data.Tick = data.TickDelay; TerrainAtlas1D atlas = game.TerrainAtlas1D; int texId = (data.TileY << 4) | data.TileX; int index = atlas.Get1DIndex(texId); int rowNum = atlas.Get1DRowId(texId); int size = data.FrameSize; byte * temp = stackalloc byte[size * size * 4]; FastBitmap part = new FastBitmap(size, size, size * 4, (IntPtr)temp); FastBitmap.MovePortion(data.FrameX + data.CurrentState * size, data.FrameY, 0, 0, fastBmp, part, size); api.UpdateTexturePart(atlas.TexIds[index], 0, rowNum * game.TerrainAtlas.elementSize, part); }
public unsafe static void DrawTiledPixels(FastBitmap src, FastBitmap dst, Rectangle srcRect, Rectangle dstRect) { int srcX = srcRect.X, srcWidth = srcRect.Width, srcHeight = srcRect.Height; int dstX, dstY, dstWidth, dstHeight; if (!CheckCoords(dst, dstRect, out dstX, out dstY, out dstWidth, out dstHeight)) { return; } for (int yy = 0; yy < dstHeight; yy++) { // srcY is always 0 so we don't need to add int *srcRow = src.GetRowPtr(((yy + dstY) % srcHeight)); int *dstRow = dst.GetRowPtr(dstY + yy); for (int xx = 0; xx < dstWidth; xx++) { dstRow[dstX + xx] = srcRow[srcX + ((xx + dstX) % srcWidth)]; } } }
public static void DrawTiled(FastBitmap src, FastBitmap dst, Rectangle srcRect, Rectangle dstRect) { int srcX = srcRect.X, srcWidth = srcRect.Width, srcHeight = srcRect.Height; int x, y, width, height; if (!Drawer2DExt.ClampCoords(dst, dstRect, out x, out y, out width, out height)) { return; } for (int yy = 0; yy < height; yy++) { // srcY is always 0 so we don't need to add int *srcRow = src.GetRowPtr(((yy + y) % srcHeight)); int *dstRow = dst.GetRowPtr(y + yy); for (int xx = 0; xx < width; xx++) { dstRow[x + xx] = srcRow[srcX + ((xx + x) % srcWidth)]; } } }
public static bool ClampCoords(FastBitmap bmp, Rectangle rect, out int x, out int y, out int width, out int height) { width = rect.Width; height = rect.Height; x = rect.X; y = rect.Y; if (x >= bmp.Width || y >= bmp.Height) { return(false); } if (x < 0) { width += x; x = 0; } if (y < 0) { height += y; y = 0; } width = Math.Min(x + width, bmp.Width) - x; height = Math.Min(y + height, bmp.Height) - y; return(width > 0 && height > 0); }
public unsafe static void DrawNoise(FastBitmap dst, Rectangle dstRect, FastColour col, int variation) { int dstX, dstY, dstWidth, dstHeight; if (!CheckCoords(dst, dstRect, out dstX, out dstY, out dstWidth, out dstHeight)) { return; } const int alpha = 255 << 24; for (int yy = 0; yy < dstHeight; yy++) { int *row = dst.GetRowPtr(dstY + yy); for (int xx = 0; xx < dstWidth; xx++) { float n = Noise(dstX + xx, dstY + yy); int r = col.R + (int)(n * variation); Utils.Clamp(ref r, 0, 255); int g = col.G + (int)(n * variation); Utils.Clamp(ref g, 0, 255); int b = col.B + (int)(n * variation); Utils.Clamp(ref b, 0, 255); row[dstX + xx] = alpha | (r << 16) | (g << 8) | b; } } }
public IDictionary <Core.Light, Core.PixelReader> Capture(ILightSetupPlugin lightSetup) { IDictionary <Core.Light, Core.PixelReader> dictionary = new Dictionary <Core.Light, Core.PixelReader>(); if (!_running) { return(dictionary); } _graphics.CopyFromScreen(_dispBounds.Left, _dispBounds.Top, 0, 0, new Size(_dispBounds.Width, _dispBounds.Height)); _fastBitmap = new FastBitmap(_img); GetCaptureSize(); foreach (Light light in lightSetup.GetLightsForBounds(_captureWidth, _captureHeight, _leftOffset, _topOffset)) { dictionary[light] = new PixelReader(_fastBitmap, light.Region); } return(dictionary); }