/// <summary> /// Moves the pencil tip to point to a specific spot, drawing between the last and new positions. /// If the operation has not been started by calling <see cref="BasicContinuousPaintOperation.StartOpertaion"/>, an exception is thrown /// </summary> /// <param name="x">The position to move the pencil tip to</param> /// <param name="y">The position to move the pencil tip to</param> /// <exception cref="InvalidOperationException">StartOperation() was not called prior to this method</exception> public void DrawTo(int x, int y) { if (!operationStarted) { throw new InvalidOperationException("The StartOperation() method must be caled prior to this method"); } Point newPencilTip = new Point(x, y); // Temporarely switch to the fast bitmap for faster plotting bool oldUseFastBitmap = useFastBitmap; if (!useFastBitmap) { fastBitmap = targetBitmap.FastLock(); useFastBitmap = true; } // Detect the algorithm to use based on the pencil's size InvokePlotsOnLine(PlotLinePoint, pencilTip, newPencilTip, Size, pencilTipPressed); // Switch back the fast bitmap in case it was previously disabled if (useFastBitmap && !oldUseFastBitmap) { fastBitmap.Dispose(); useFastBitmap = false; } pencilTipPressed = true; pencilTip = newPencilTip; }
public Bitmap ToGrayscale(Bitmap originalBmp, bool parallel) { FastBitmap fastOriginal = new FastBitmap(originalBmp); int h = originalBmp.Height, w = originalBmp.Width; if (parallel) { Parallel.For(0, h, (y) => { Parallel.For(0, w, (x) => { Color c = fastOriginal.GetColor(x, y); int gray = (byte)(c.R * 0.11 + c.G * 0.59 + c.R * 0.3); fastOriginal.SetColor(x, y, Color.FromArgb(gray, gray, gray)); }); }); } else { for (int y = 0; y < originalBmp.Height; y++) { for (int x = 0; x < originalBmp.Width; x++) { Color c = fastOriginal.GetColor(x, y); int gray = (byte)(c.R * 0.11 + c.G * 0.59 + c.R * 0.3); fastOriginal.SetColor(x, y, Color.FromArgb(gray, gray, gray)); } } } fastOriginal.Dispose(); return(originalBmp); }
// метод, возвращающий изображение фрактала с учетом алгоритма и цветовой схемы (NormalizedIterationCountAlgorithm) private Bitmap NormalizedIterationCountAlgorithm(int[,] fractalMatrix) { var bmp = new Bitmap(generationSettings.Resolution.Width / generationSettings.QualityFactor, generationSettings.Resolution.Height / generationSettings.QualityFactor); var fb = new FastBitmap(bmp); PixelData pData; for (var i = 0; i < generationSettings.Resolution.Width / generationSettings.QualityFactor; i++) { for (var j = 0; j < generationSettings.Resolution.Height / generationSettings.QualityFactor; j++) { if (fractalMatrix[i, j] > generationSettings.IterationCount) { pData.R = colorSettings.NotFractalPointsColor.R; pData.G = colorSettings.NotFractalPointsColor.G; pData.B = colorSettings.NotFractalPointsColor.B; } else { double t = fractalMatrix[i, j] / (double)generationSettings.IterationCount; pData.R = (byte)(9 * (1 - t) * t * t * t * colorSettings.R); pData.G = (byte)(15 * (1 - t) * (1 - t) * t * t * colorSettings.G); pData.B = (byte)(8.5 * (1 - t) * (1 - t) * (1 - t) * t * colorSettings.B); } fb.SetPixelData(i, j, pData); } } fb.Dispose(); return(bmp); }
// Updates Tilemap image (forced redraw) private void UpdateTilemap() { if (tilemap == null || tileset == null) { return; } ignore = true; // set size info tTilemapWidth.Value = tilemap.Width; tTilemapHeight.Value = tilemap.Height; // draw tilemap if (tilemapImage == null) { tilemapImage = new FastBitmap(tilemap.Width * 8, tilemap.Height * 8); } if (tilemapImage.Width != tilemap.Width * 8 || tilemapImage.Height != tilemap.Height * 8) { tilemapImage.Dispose(); tilemapImage = new FastBitmap(tilemap.Width * 8, tilemap.Height * 8); } tilemap.Draw(tilemapImage, tileset); // finished pTilemap.Size = new Size(tilemapImage.Width * zoom, tilemapImage.Height * zoom); pTilemap.Image = tilemapImage; ignore = false; }
// метод, возвращающий изображение фрактала с учетом алгоритма и цветовой схемы (EscapeTimeAlgorithm) private Bitmap EscapeTimeAlgorithm(int[,] fractalMatrix) { var bmp = new Bitmap(generationSettings.Resolution.Width / generationSettings.QualityFactor, generationSettings.Resolution.Height / generationSettings.QualityFactor); var fb = new FastBitmap(bmp); PixelData pData; for (var i = 0; i < generationSettings.Resolution.Width / generationSettings.QualityFactor; i++) { for (var j = 0; j < generationSettings.Resolution.Height / generationSettings.QualityFactor; j++) { if (fractalMatrix[i, j] > generationSettings.IterationCount) { pData.R = colorSettings.NotFractalPointsColor.R; pData.G = colorSettings.NotFractalPointsColor.G; pData.B = colorSettings.NotFractalPointsColor.B; } else { pData.B = (byte)((fractalMatrix[i, j] * 20) % colorSettings.B); pData.G = (byte)((fractalMatrix[i, j] * 15) % colorSettings.G); pData.R = (byte)((fractalMatrix[i, j] * 10) % colorSettings.R); } fb.SetPixelData(i, j, pData); } } fb.Dispose(); return(bmp); }
/// <summary> /// The FastBitmap created to wrap the capture during the capture is disposed of here /// </summary> public void ReleaseCapture() { if (_fastBitmap != null) { _fastBitmap.Dispose(); _fastBitmap = null; } }
public void Unlock() { if (fastImage != null) { fastImage.UnlockBitmap(); fastImage.Dispose(); fastImage = null; } }
/// <summary> Disposes the atlas bitmap that contains animation frames, and clears /// the list of defined animations. </summary> public void Dispose() { animations.Clear(); if (bmp == null) { return; } fastBmp.Dispose(); bmp.Dispose(); bmp = null; }
private unsafe bool FindEyes(out EyeData leftEye, out EyeData rightEye) { const byte DifferenceThreshold = 25; int[,] changeCount = new int[workerImageArray[0].Width, workerImageArray[0].Height]; for (int i = 0; i < workerImageArray.Length - 1; ++i) { FastBitmap differenceImage = workerImageArray[i].GetDifferenceImage(workerImageArray[i + 1], DifferenceThreshold); FastBitmap erosionImage = differenceImage.ApplyCrossErosionMask(); ColorARGB *currentPosition = erosionImage.StartingPosition; for (int y = 0; y < erosionImage.Height; ++y) { for (int x = 0; x < erosionImage.Width; ++x) { if (currentPosition->B == 255) { ++changeCount[x, y]; } ++currentPosition; } } differenceImage.Dispose(); erosionImage.Dispose(); } FastBitmap finalDifferenceImage = new FastBitmap(workerImageArray[0].Width, workerImageArray[0].Height); ColorARGB *currentPositionResult = finalDifferenceImage.StartingPosition; for (int y = 0; y < finalDifferenceImage.Height; ++y) { for (int x = 0; x < finalDifferenceImage.Width; ++x) { byte color = 0; if (changeCount[x, y] > 0) { color = 255; } currentPositionResult->A = 255; currentPositionResult->R = color; currentPositionResult->G = color; currentPositionResult->B = color; ++currentPositionResult; } } return(FindEyesFromDifferenceImage(workerImageArray[workerImageArray.Length - 1], finalDifferenceImage, out leftEye, out rightEye)); }
/// <summary> Disposes the atlas bitmap that contains animation frames, and clears /// the list of defined animations. </summary> public void Clear() { animations.Clear(); if (animBmp == null) { return; } animsBuffer.Dispose(); animsBuffer = null; animBmp.Dispose(); animBmp = null; validated = false; }
public void Process() { int photosPerPart = ImportFilenames.Length / PartAmount; int curIndex = 0; RawImage[] parts = new RawImage[PartAmount]; for (int i = 0; i < PartAmount; i++) { string[] filenames = new string[photosPerPart]; for (int j = 0; j < photosPerPart; j++) { filenames[j] = ImportFilenames[curIndex++]; } parts[i] = ProcessPart(filenames); ParentForm.progressBar.Increment(1); } RawImage finalOutput = new RawImage(Width, Height); for (int y = 0; y < Height; y++) { for (int x = 0; x < Width; x++) { RawColor outputColor = new RawColor(); for (int i = 0; i < parts.Length; i++) { outputColor += parts[i].RawColors[x, y]; } finalOutput.RawColors[x, y] = outputColor; } } FastBitmap finalImage = new FastBitmap(Width, Height); for (int y = 0; y < Height; y++) { Application.DoEvents(); for (int x = 0; x < Width; x++) { finalImage.SetPixel(x, y, (FastColor)finalOutput.RawColors[x, y]); } } finalImage.Save(ExportFilename); finalImage.Dispose(); }
private void DisposeInner() { foreach (FastBitmap sample in _samples) { if (!sample.Locked) { sample.Dispose(); } } if (!_territoryData.Locked) { _territoryData.Dispose(); } }
public void ReleaseCapture() { if (_fastBitmap != null) { _fastBitmap.Dispose(); _fastBitmap = null; } if (_capturedImage != null) { _capturedImage.Dispose(); _capturedImage = null; } }
// updates Tileset size and image void UpdateTileset(bool clearSelection) { if (tileset == null) { return; } ignore = true; if (rModeTilemap.Checked) { // get Tileset size int width = cTilesetWidth.Value; if (width <= 0) { width = 1; } int height = (tileset.Length / width) + (tileset.Length % width > 0 ? 1 : 0); // update height text tTilesetHeight.Value = height; // update Tileset image tilesetImage?.Dispose(); tilesetImage = tileset.ToImage(width); pTileset.Size = new Size(tilesetImage.Width * zoom, tilesetImage.Height * zoom); pTileset.Image = tilesetImage; if (clearSelection) { tilesetSelection = new Rectangle(0, 0, 1, 1); } lTilesetSelection.Text = rModeTilemap.Checked ? $"({tilesetSelection.X}, {tilesetSelection.Y}) to ({tilesetSelection.X + tilesetSelection.Width - 1}, {tilesetSelection.Y + tilesetSelection.Height - 1})" : $"{paletteSelection}"; } else { pTileset.Size = new Size(palettesetImage.Width * zoom, palettesetImage.Height * zoom); pTileset.Image = palettesetImage; } ignore = false; }
public Bitmap convertToGray(Bitmap originalBmp) { FastBitmap fastOriginal = new FastBitmap(originalBmp); int h = originalBmp.Height, w = originalBmp.Width; for (int y = 0; y < originalBmp.Height; y++) { for (int x = 0; x < originalBmp.Width; x++) { Color c = fastOriginal.GetColor(x, y); int gray = (byte)(c.R * 0.11 + c.G * 0.59 + c.R * 0.3); fastOriginal.SetColor(x, y, Color.FromArgb(gray, gray, gray)); } } fastOriginal.Dispose(); return(originalBmp); }
// protected protected override void OnSizeChanged(EventArgs e) { if (surface != null) { surface.Dispose(); } if (Width > 0 && Height > 0) { surface = new FastBitmap(Width, Height, ColorBgra.White); graphics.Graphics = surface.Graphics; baseControl.surface = surface; } else { surface = null; } }
private void GetTrackingPoints(FastBitmap img, EyeData leftEye, EyeData rightEye) { const int YDownShift = 30; const int XExpand = 5; const float eyebrowMult = 0.6f; int eyebrowWidth = (int)Math.Abs((leftEye.loc.X - rightEye.loc.X) * eyebrowMult); Rectangle searchArea = new Rectangle(); FastBitmap smoothed = img.GaussianSmooth(5); FastBitmap sobel = smoothed.SobelGradient(); smoothed.Dispose(); searchArea.Y = Math.Max(leftEye.loc.Y, rightEye.loc.Y) + YDownShift; searchArea.X = leftEye.loc.X - XExpand; searchArea.Width = rightEye.loc.X - leftEye.loc.X + (2 * XExpand); searchArea.Height = (int)((rightEye.loc.X - leftEye.loc.X) * 0.6f); float[,] trackingPointScores = new float[searchArea.Width, searchArea.Height]; for (int x = searchArea.Left; x < searchArea.Right; ++x) { for (int y = searchArea.Top; y < searchArea.Bottom; ++y) { float score = 0; for (int i = 0; i < TrackingPointWidth; ++i) { for (int j = 0; j < TrackingPointWidth; ++j) { score += sobel.GetIntensity(x + i, y + j); } } trackingPointScores[x - searchArea.Left, y - searchArea.Top] = score; } } mouseTrackingPoint = GetBestTrackingPointWithinColumn(trackingPointScores, searchArea, (leftEye.loc.X + rightEye.loc.X) / 2); leftEyeTrackingPoint = GetBestTrackingForEye(sobel, leftEye, eyebrowWidth); rightEyeTrackingPoint = GetBestTrackingForEye(sobel, rightEye, eyebrowWidth); sobel.Dispose(); }
public static Bitmap Photo2Bitmap(Photo photo) { Bitmap bmp = new Bitmap(photo.Width, photo.Height); FastBitmap fbmp = new FastBitmap(bmp); fbmp.Lock(); for (int x = 0; x < bmp.Width; x++) { for (int y = 0; y < bmp.Height; y++) { fbmp.SetPixel(x, y, Color.FromArgb((byte)((photo[x, y].A) * 255), (byte)((photo[x, y].R) * 255), (byte)((photo[x, y].G) * 255), (byte)((photo[x, y].B) * 255))); } } fbmp.Dispose(); return(bmp); }
WorldTileEntity[,] LoadWorldTiles(string worldId) { ConcurrentDictionary <int, string> provinceColourIds = new ConcurrentDictionary <int, string>(); ConcurrentDictionary <int, string> biomeColourIds = new ConcurrentDictionary <int, string>(); IBiomeRepository biomeRepository = new BiomeRepository(Path.Combine(worldsDirectory, worldId, "biomes.xml")); IProvinceRepository provinceRepository = new ProvinceRepository(Path.Combine(worldsDirectory, worldId, "provinces.xml")); Parallel.ForEach(biomeRepository.GetAll(), b => biomeColourIds.AddOrUpdate(ColorTranslator.FromHtml(b.ColourHexadecimal).ToArgb(), b.Id)); Parallel.ForEach(provinceRepository.GetAll(), r => provinceColourIds.AddOrUpdate(ColorTranslator.FromHtml(r.ColourHexadecimal).ToArgb(), r.Id)); FastBitmap biomeBitmap = new FastBitmap(Path.Combine(worldsDirectory, worldId, "biomes_map.png")); FastBitmap provinceBitmap = new FastBitmap(Path.Combine(worldsDirectory, worldId, "map.png")); Point worldSize = new Point(Math.Max(biomeBitmap.Width, provinceBitmap.Width), Math.Max(biomeBitmap.Height, provinceBitmap.Height)); WorldTileEntity[,] tiles = new WorldTileEntity[provinceBitmap.Width, provinceBitmap.Height]; Parallel.For(0, worldSize.Y, y => Parallel.For(0, worldSize.X, x => tiles[x, y] = new WorldTileEntity())); biomeBitmap.LockBits(); provinceBitmap.LockBits(); Parallel.For(0, biomeBitmap.Height, y => Parallel.For(0, biomeBitmap.Width, x => { int argb = biomeBitmap.GetPixel(x, y).ToArgb(); tiles[x, y].BiomeId = biomeColourIds[argb]; })); Parallel.For(0, provinceBitmap.Height, y => Parallel.For(0, provinceBitmap.Width, x => { int argb = provinceBitmap.GetPixel(x, y).ToArgb(); tiles[x, y].ProvinceId = provinceColourIds[argb]; })); biomeBitmap.Dispose(); provinceBitmap.Dispose(); return(tiles); }
public void Blur(Int32 horz, Int32 vert) { Single weightsum; Single[] weights; FastBitmap t = (FastBitmap)_bitmap.Clone(); _bitmap.Lock(); t.Lock(); weights = new Single[horz * 2 + 1]; for (Int32 i = 0; i < horz * 2 + 1; i++) { Single y = Gauss(-horz + i, 0, horz); weights[i] = y; } for (Int32 row = 0; row < _bitmap.Height; row++) { for (Int32 col = 0; col < _bitmap.Width; col++) { Double r = 0; Double g = 0; Double b = 0; weightsum = 0; for (Int32 i = 0; i < horz * 2 + 1; i++) { Int32 x = col - horz + i; if (x < 0) { i += -x; x = 0; } if (x > _bitmap.Width - 1) { break; } Color c = _bitmap.GetPixel(x, row); r += c.R * weights[i]; g += c.G * weights[i]; b += c.B * weights[i]; weightsum += weights[i]; } r /= weightsum; g /= weightsum; b /= weightsum; Byte br = (Byte)Math.Round(r); Byte bg = (Byte)Math.Round(g); Byte bb = (Byte)Math.Round(b); if (br > 255) { br = 255; } if (bg > 255) { bg = 255; } if (bb > 255) { bb = 255; } t.SetPixel(col, row, Color.FromArgb(br, bg, bb)); } } weights = new Single[vert * 2 + 1]; for (Int32 i = 0; i < vert * 2 + 1; i++) { Single y = Gauss(-vert + i, 0, vert); weights[i] = y; } for (Int32 col = 0; col < _bitmap.Width; col++) { for (Int32 row = 0; row < _bitmap.Height; row++) { Double r = 0; Double g = 0; Double b = 0; weightsum = 0; for (Int32 i = 0; i < vert * 2 + 1; i++) { Int32 y = row - vert + i; if (y < 0) { i += -y; y = 0; } if (y > _bitmap.Height - 1) { break; } Color c = t.GetPixel(col, y); r += c.R * weights[i]; g += c.G * weights[i]; b += c.B * weights[i]; weightsum += weights[i]; } r /= weightsum; g /= weightsum; b /= weightsum; Byte br = (Byte)Math.Round(r); Byte bg = (Byte)Math.Round(g); Byte bb = (Byte)Math.Round(b); if (br > 255) { br = 255; } if (bg > 255) { bg = 255; } if (bb > 255) { bb = 255; } _bitmap.SetPixel(col, row, Color.FromArgb(br, bg, bb)); } } t.Dispose(); _bitmap.Unlock(); }
/// <summary> /// Creates a new image of the specified size from the source image /// </summary> /// <param name="src">Source image path</param> /// <param name="dest">Destination image path</param> /// <param name="imgCfg">The configuration of the image</param> /// <param name="forceUpdate">Update in every case</param> /// <param name="jpegQuality">The Quality for the JPEG File 0..100</param> public void CreateShadowedImage(string src, string dest, ImageBrowserConfig.ImageCfg imgCfg, bool forceUpdate, byte jpegQuality) { try { if (!forceUpdate && File.Exists(cfg.PictureRootDirectory + "/" + dest)) { return; } string path = Directory.GetParent(cfg.PictureRootDirectory + "/" + dest).FullName; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } // Values for building Shadow. Int32 shadowwidth = imgCfg.ShadowWidth; Int32 borderwidth = imgCfg.BorderWidth; Int32 margin = shadowwidth / 2; Int32 shadowdir = 0; Double shadowtrans = imgCfg.ShadowTransparency; Color bkcolor = Color.FromArgb(imgCfg.BackgroundColor); Color shadowcolor = Color.FromArgb(imgCfg.ShadowColor); Color bordercolor = Color.FromArgb(imgCfg.BorderColor); Boolean softshadow = imgCfg.SoftShadow; Image thumb = CreateImageInternal(src, imgCfg.MaxSize); if (thumb != null) { FastBitmap tmp = new FastBitmap(thumb); FastBitmap bmp = new FastBitmap(tmp.Width + borderwidth * 2, tmp.Height + borderwidth * 2, PixelFormat.Format32bppArgb); // add border if necessary if (borderwidth > 0) { using (SolidBrush br = new SolidBrush(bordercolor)) using (Graphics g = Graphics.FromImage(bmp._bitmap)) { g.FillRectangle(br, 0, 0, borderwidth * 2 + tmp.Width, borderwidth * 2 + tmp.Height); } } tmp.CopyTo(bmp, borderwidth, borderwidth, 0, 0, tmp.Width, tmp.Height); tmp.Dispose(); // create image Int32 width = bmp.Width + shadowwidth + margin * 2; Int32 height = bmp.Height + shadowwidth + margin * 2; LayeredImage image = new LayeredImage(width, height); Int32 shadowx = 0, shadowy = 0, imgx = 0, imgy = 0; if (softshadow) { switch (shadowdir) { case 0: shadowx = margin - shadowwidth / 2; shadowy = margin - shadowwidth / 2; imgx = margin; imgy = margin; break; case 1: shadowx = margin + shadowwidth - 3 * (shadowwidth / 2); shadowy = margin - shadowwidth / 2; imgx = margin + shadowwidth; imgy = margin; break; case 2: shadowx = margin + shadowwidth - 3 * (shadowwidth / 2); shadowy = margin + shadowwidth - 3 * (shadowwidth / 2); imgx = margin + shadowwidth; imgy = margin + shadowwidth; break; case 3: shadowx = margin - shadowwidth / 2; shadowy = margin + shadowwidth - 3 * (shadowwidth / 2); imgx = margin; imgy = margin + shadowwidth; break; } } else { switch (shadowdir) { case 0: shadowx = margin; shadowy = margin; imgx = margin; imgy = margin; break; case 1: shadowx = margin - shadowwidth; shadowy = margin; imgx = margin + shadowwidth; imgy = margin; break; case 2: shadowx = margin - shadowwidth; shadowy = margin - shadowwidth; imgx = margin + shadowwidth; imgy = margin + shadowwidth; break; case 3: shadowx = margin; shadowy = margin - shadowwidth; imgx = margin; imgy = margin + shadowwidth; break; } } // background Layer bg = image.Layers.Add(); bg.Clear(bkcolor); // shadow -- layer must be larger because of blur Layer shadow = image.Layers.Add(width + shadowwidth, height + shadowwidth); SolidBrush brush = new SolidBrush(shadowcolor); shadow.FillRectangle(shadowwidth, shadowwidth, bmp.Width, bmp.Height, brush); if (softshadow) { shadow.Blur(shadowwidth, shadowwidth); } brush.Dispose(); shadow.OffsetX = shadowx; shadow.OffsetY = shadowy; shadow.Opacity = 1.0 - shadowtrans; // image Layer img = image.Layers.Add(bmp); img.OffsetX = imgx; img.OffsetY = imgy; // result FastBitmap result = image.Flatten(); EncoderParameters encParams = new EncoderParameters(1); encParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)jpegQuality); result.Save(cfg.PictureRootDirectory + "/" + dest, GetEncoder(ImageFormat.Jpeg), encParams); result.Dispose(); } } catch (Exception) {} }
/// <summary> /// Creates a new image of the specified size from the source image /// </summary> /// <param name="src">Source image path</param> /// <param name="dest">Destination image path</param> /// <param name="imgCfg">The configuration of the image</param> /// <param name="forceUpdate">Update in every case</param> /// <param name="jpegQuality">The Quality for the JPEG File 0..100</param> public void CreateShadowedImage(string src, string dest, ImageBrowserConfig.ImageCfg imgCfg, bool forceUpdate, byte jpegQuality) { try { if (!forceUpdate && File.Exists(cfg.PictureRootDirectory + "/" + dest) ) return; string path = Directory.GetParent(cfg.PictureRootDirectory + "/" + dest).FullName; if ( ! Directory.Exists(path)) Directory.CreateDirectory(path); // Values for building Shadow. Int32 shadowwidth = imgCfg.ShadowWidth; Int32 borderwidth = imgCfg.BorderWidth; Int32 margin = shadowwidth / 2; Int32 shadowdir = 0; Double shadowtrans = imgCfg.ShadowTransparency; Color bkcolor = Color.FromArgb(imgCfg.BackgroundColor); Color shadowcolor = Color.FromArgb(imgCfg.ShadowColor); Color bordercolor = Color.FromArgb(imgCfg.BorderColor); Boolean softshadow = imgCfg.SoftShadow; Image thumb = CreateImageInternal(src, imgCfg.MaxSize); if(thumb != null) { FastBitmap tmp = new FastBitmap(thumb); FastBitmap bmp = new FastBitmap(tmp.Width + borderwidth * 2, tmp.Height + borderwidth * 2, PixelFormat.Format32bppArgb); // add border if necessary if (borderwidth > 0) { using(SolidBrush br = new SolidBrush(bordercolor)) using (Graphics g = Graphics.FromImage(bmp._bitmap)) { g.FillRectangle(br, 0, 0, borderwidth * 2 + tmp.Width, borderwidth * 2 + tmp.Height); } } tmp.CopyTo(bmp, borderwidth, borderwidth, 0, 0, tmp.Width, tmp.Height); tmp.Dispose(); // create image Int32 width = bmp.Width + shadowwidth + margin * 2; Int32 height = bmp.Height + shadowwidth + margin * 2; LayeredImage image = new LayeredImage(width, height); Int32 shadowx = 0, shadowy = 0, imgx = 0, imgy = 0; if (softshadow) { switch (shadowdir) { case 0: shadowx = margin - shadowwidth / 2; shadowy = margin - shadowwidth / 2; imgx = margin; imgy = margin; break; case 1: shadowx = margin + shadowwidth - 3 * (shadowwidth / 2); shadowy = margin - shadowwidth / 2; imgx = margin + shadowwidth; imgy = margin; break; case 2: shadowx = margin + shadowwidth - 3 * (shadowwidth / 2); shadowy = margin + shadowwidth - 3 * (shadowwidth / 2); imgx = margin + shadowwidth; imgy = margin + shadowwidth; break; case 3: shadowx = margin - shadowwidth / 2; shadowy = margin + shadowwidth - 3 * (shadowwidth / 2); imgx = margin; imgy = margin + shadowwidth; break; } } else { switch (shadowdir) { case 0: shadowx = margin; shadowy = margin; imgx = margin; imgy = margin; break; case 1: shadowx = margin - shadowwidth; shadowy = margin; imgx = margin + shadowwidth; imgy = margin; break; case 2: shadowx = margin - shadowwidth; shadowy = margin - shadowwidth; imgx = margin + shadowwidth; imgy = margin + shadowwidth; break; case 3: shadowx = margin; shadowy = margin - shadowwidth; imgx = margin; imgy = margin + shadowwidth; break; } } // background Layer bg = image.Layers.Add(); bg.Clear(bkcolor); // shadow -- layer must be larger because of blur Layer shadow = image.Layers.Add(width + shadowwidth, height + shadowwidth); SolidBrush brush = new SolidBrush(shadowcolor); shadow.FillRectangle(shadowwidth, shadowwidth, bmp.Width, bmp.Height, brush); if (softshadow) shadow.Blur(shadowwidth, shadowwidth); brush.Dispose(); shadow.OffsetX = shadowx; shadow.OffsetY = shadowy; shadow.Opacity = 1.0 - shadowtrans; // image Layer img = image.Layers.Add(bmp); img.OffsetX = imgx; img.OffsetY = imgy; // result FastBitmap result = image.Flatten(); EncoderParameters encParams = new EncoderParameters(1); encParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long) jpegQuality); result.Save(cfg.PictureRootDirectory + "/" + dest, GetEncoder(ImageFormat.Jpeg), encParams); result.Dispose(); } } catch(Exception){} }
public static void DoMakeObjFile(string outputDir, string inputFile, string gradient, string emissive) { byte[] gradientColors = gradient.Split(new char[] { '[', ']', ',' }, StringSplitOptions.RemoveEmptyEntries).Select(cur => byte.Parse(cur.Trim())).ToArray(); SColor[] gradientObj = new SColor[] { new SColor { R = gradientColors[0], B = gradientColors[1], G = gradientColors[2] }, new SColor { R = gradientColors[3], B = gradientColors[4], G = gradientColors[5] }, new SColor { R = gradientColors[6], B = gradientColors[7], G = gradientColors[8] }, }; byte[] emissiveColors = emissive.Split(new char[] { '[', ']', ',' }, StringSplitOptions.RemoveEmptyEntries).Select(cur => byte.Parse(cur.Trim())).ToArray(); SColor emissiveObj = new SColor { R = emissiveColors[0], B = emissiveColors[1], G = emissiveColors[2] }; string inputOrg = inputFile; bool isJson = inputFile.EndsWith(".json", StringComparison.OrdinalIgnoreCase); bool isMsgpack = inputFile.EndsWith(".msgpack", StringComparison.OrdinalIgnoreCase); if (!File.Exists(inputFile) || (!isMsgpack && !isJson)) { throw new Exception("Input file must be .msgpack or .json"); } if (!Directory.Exists(outputDir)) { throw new Exception("Output directory does not exist!"); } if (isMsgpack) { Parser.DoParse(outputDir, inputFile); inputFile = Path.Combine(outputDir, $"{Path.GetFileNameWithoutExtension(inputFile)}.json"); } string materialName = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(inputFile)); string materialFile = $"{materialName}.mtl"; string materialFilePath = Path.Combine(outputDir, materialFile); JObject root = JObject.Parse(File.ReadAllText(inputFile)); Dictionary <string, Dictionary <string, string> > materialLookup = new Dictionary <string, Dictionary <string, string> >(); foreach (var curNode in root["nodes"].Value <JObject>()) { if (!curNode.Value.Value <JObject>().ContainsKey("geometryinstances")) { continue; } foreach (var curGeom in curNode.Value["geometryinstances"].Value <JObject>()) { string geometry = curGeom.Value["geometry"].Value <string>(); string surface = curGeom.Value["surface"].Value <string>(); string material = curGeom.Value["material"].Value <string>(); if (!materialLookup.TryGetValue(geometry, out Dictionary <string, string> curGeomLookup)) { curGeomLookup = new Dictionary <string, string>(); materialLookup.Add(geometry, curGeomLookup); } curGeomLookup[surface] = material; } } bool failMat = false; string outputFile = Path.Combine(outputDir, $"{Path.GetFileNameWithoutExtension(inputFile)}.obj"); using (StreamWriter sw = new StreamWriter(outputFile)) { sw.WriteLine($"mtllib {materialFile}"); int vOffset = 0; int vtOffset = 0; int vnOffset = 0; foreach (var curGeom in root["geometries"].Value <JObject>()) { // TODO: handle TANGENT and BINORMAL. Anymore? //if (curGeom.Value["inputs"].Count() != 3) //{ // throw new Exception("Invalid source input count..."); //} double[][] vertLocs = ReadShit <double>(curGeom.Value, "POSITION", out int vertOffset); foreach (double[] curVert in vertLocs) { sw.WriteLine($"v {curVert[0]} {curVert[1]} {curVert[2]}"); } double[][] texCoords = ReadShit <double>(curGeom.Value, "TEXCOORD0", out int texOffset); foreach (double[] curTex in texCoords) { sw.WriteLine($"vt {curTex[0]} {1-curTex[1]}"); } double[][] normals = ReadShit <double>(curGeom.Value, "NORMAL", out int normOffset); foreach (double[] curNorm in normals) { sw.WriteLine($"vn {curNorm[0]} {curNorm[1]} {curNorm[2]}"); } foreach (var curSurf in curGeom.Value["surfaces"].Value <JObject>()) { sw.WriteLine($"g {curSurf.Key}"); try { sw.WriteLine($"usemtl {materialLookup[curGeom.Key][curSurf.Key]}"); } catch { failMat = true; sw.WriteLine($"usemtl failMat"); Console.WriteLine("material not found..."); } var blarg = curSurf.Value["triangles"].Select(cur => cur.Value <int>()); int numPrimitives = curSurf.Value["numPrimitives"].Value <int>(); if ((blarg.Count() % numPrimitives) != 0) { throw new Exception("Invalid stride"); } int stride = blarg.Count() / numPrimitives; if ((stride % 3) != 0) { throw new Exception("Invalid stride"); } int pointLength = stride / 3; int[][] triangles = FuckinReadIt(blarg, stride); foreach (int[] curTri in triangles) { if (pointLength >= 1) { if ((curTri[pointLength * 0 + 0] >= vertLocs.Length) || (curTri[pointLength * 1 + 0] >= vertLocs.Length) || (curTri[pointLength * 2 + 0] >= vertLocs.Length)) { Console.WriteLine("vert index out of range"); continue; } } if (pointLength >= 2) { if ((curTri[pointLength * 0 + 1] >= texCoords.Length) || (curTri[pointLength * 1 + 1] >= texCoords.Length) || (curTri[pointLength * 2 + 1] >= texCoords.Length)) { Console.WriteLine("tex index out of range"); continue; } } if (pointLength >= 3) { if ((curTri[pointLength * 0 + 2] >= normals.Length) || (curTri[pointLength * 1 + 2] >= normals.Length) || (curTri[pointLength * 2 + 2] >= normals.Length)) { Console.WriteLine("norm index out of range"); continue; } } sw.Write("f"); for (int i = 0; i < 3; ++i) { sw.Write(" "); if (pointLength >= 1) { sw.Write($"{curTri[pointLength * i + 0] + 1 + vOffset}"); } if (pointLength >= 2) { sw.Write($"/{curTri[pointLength * i + 1] + 1 + vtOffset}"); } if (pointLength >= 3) { sw.Write($"/{curTri[pointLength * i + 2] + 1 + vnOffset}"); } } sw.WriteLine(); } } vOffset += vertLocs.Length; vtOffset += texCoords.Length; vnOffset += normals.Length; } sw.Flush(); sw.Close(); sw.Dispose(); } string rootDir = inputOrg; while (Path.GetFileName(rootDir) != "assets") { rootDir = Path.GetDirectoryName(rootDir); } using (StreamWriter sw = new StreamWriter(materialFilePath)) { foreach (var curMat in root["materials"].Value <JObject>()) { sw.WriteLine($"newmtl {curMat.Key}"); var material = curMat.Value.Value <JObject>(); int usedTextures = 0; if (material["parameters"].Value <JObject>().ContainsKey("diffuse") || material["parameters"].Value <JObject>().ContainsKey("gradient_mask")) { string diffuse; FastBitmap diffuseTexture; if (material["parameters"].Value <JObject>().ContainsKey("diffuse")) { ++usedTextures; diffuse = material["parameters"]["diffuse"].Value <string>().Replace('/', '\\'); try { diffuseTexture = DDS.LoadImage(Path.Combine(rootDir, diffuse)).FastLock(); } catch { diffuseTexture = null; Console.WriteLine("Error loading texture"); } } else { diffuse = material["parameters"]["gradient_mask"].Value <string>().Replace('/', '\\'); diffuseTexture = null; } if (material["parameters"].Value <JObject>().ContainsKey("gradient_mask")) { ++usedTextures; string gradient_mask = material["parameters"]["gradient_mask"].Value <string>().Replace('/', '\\'); FastBitmap gradient_maskTexture = null; bool fail = false; try { gradient_maskTexture = DDS.LoadImage(Path.Combine(rootDir, gradient_mask)).FastLock(); } catch { fail = true; Console.WriteLine("Error loading texture"); } if (!fail) { if (diffuseTexture == null) { diffuseTexture = new Bitmap(gradient_maskTexture.Width, gradient_maskTexture.Height, PixelFormat.Format32bppArgb).FastLock(); } ApplyGradientToDiffuse(diffuseTexture, gradient_maskTexture, gradientObj); gradient_maskTexture.Unlock(); gradient_maskTexture.Bitmap.Dispose(); gradient_maskTexture.Dispose(); } } if (diffuseTexture == null) { diffuseTexture = new Bitmap(512, 512, PixelFormat.Format32bppArgb).FastLock(); SetFlatColor(diffuseTexture, new SColor { R = 255, G = 0, B = 255 }); } diffuseTexture.Unlock(); string saveFilePath = Path.Combine(outputDir, $"{Path.GetFileNameWithoutExtension(diffuse)}.png"); sw.WriteLine($"map_Kd {Path.GetFileName(saveFilePath)}"); try { diffuseTexture.Bitmap.Save(saveFilePath, ImageFormat.Png); } catch (Exception ex) { Console.WriteLine($"Failed to save image {saveFilePath}\r\n{ex.Message}"); } diffuseTexture.Bitmap.Dispose(); diffuseTexture.Dispose(); } if (material["parameters"].Value <JObject>().ContainsKey("normal")) { ++usedTextures; string normal = material["parameters"]["normal"].Value <string>().Replace('/', '\\'); FastBitmap normalTexture = null; bool fail = false; try { normalTexture = DDS.LoadImage(Path.Combine(rootDir, normal)).FastLock(); } catch { fail = true; Console.WriteLine("Error loading texture"); } if (!fail) { normalTexture.Unlock(); string saveFilePath = Path.Combine(outputDir, $"{Path.GetFileNameWithoutExtension(normal)}.png"); sw.WriteLine($"map_Bump {Path.GetFileName(saveFilePath)}"); try { normalTexture.Bitmap.Save(saveFilePath, ImageFormat.Png); } catch (Exception ex) { Console.WriteLine($"Failed to save image {saveFilePath}\r\n{ex.Message}"); } normalTexture.Bitmap.Dispose(); normalTexture.Dispose(); } } if (material["parameters"].Value <JObject>().ContainsKey("specular_emissive")) { ++usedTextures; string specular_emissive = material["parameters"]["specular_emissive"].Value <string>().Replace('/', '\\'); FastBitmap specular_emissiveTexture = null; bool fail = false; try { specular_emissiveTexture = DDS.LoadImage(Path.Combine(rootDir, specular_emissive)).FastLock(); } catch { fail = true; Console.WriteLine("Error loading texture"); } if (!fail) { ApplyEmissiveColor(specular_emissiveTexture, emissiveObj); specular_emissiveTexture.Unlock(); string saveFilePath = Path.Combine(outputDir, $"{Path.GetFileNameWithoutExtension(specular_emissive)}.png"); sw.WriteLine($"map_Ke {Path.GetFileName(saveFilePath)}"); try { specular_emissiveTexture.Bitmap.Save(saveFilePath, ImageFormat.Png); } catch (Exception ex) { Console.WriteLine($"Failed to save image {saveFilePath}\r\n{ex.Message}"); } specular_emissiveTexture.Bitmap.Dispose(); specular_emissiveTexture.Dispose(); } } if (material["parameters"].Value <JObject>().Count != usedTextures) { Console.WriteLine($"Warning, unused texture(s) on {curMat.Key}..."); } } if (failMat) { FastBitmap failTexture = new Bitmap(512, 512, PixelFormat.Format32bppArgb).FastLock(); SetFlatColor(failTexture, new SColor { R = 255, G = 0, B = 255 }); sw.WriteLine($"newmtl failMat"); failTexture.Unlock(); string saveFilePath = Path.Combine(outputDir, $"failMat.png"); sw.WriteLine($"map_Kd {Path.GetFileName(saveFilePath)}"); try { failTexture.Bitmap.Save(saveFilePath, ImageFormat.Png); } catch (Exception ex) { Console.WriteLine($"Failed to save image {saveFilePath}\r\n{ex.Message}"); } failTexture.Bitmap.Dispose(); failTexture.Dispose(); } sw.Flush(); sw.Close(); sw.Dispose(); } Console.WriteLine("Done Done!!!"); }
public void Dispose() { Image.Dispose(); }
private void MakeDistortionGrid() { Bitmap bmpBlend = new Bitmap(config.BlendFile); FastBitmap fastBlend = new FastBitmap(bmpBlend); Bitmap bmpDistort = new Bitmap(config.DistortionGrid); FastBitmap fastDistort = new FastBitmap(bmpDistort); fastBlend.LockBitmapRgb(); fastDistort.LockBitmapRgb(); int subX = bmpBlend.Width - 1; int subY = subX; if (distortIndexBuffer != null) { distortIndexBuffer.Dispose(); GC.SuppressFinalize(distortIndexBuffer); } if (distortVertexBuffer != null) { distortVertexBuffer.Dispose(); GC.SuppressFinalize(distortVertexBuffer); } distortIndexBuffer = new IndexBuffer11(typeof(int), (subX * subY * 6), RenderContext11.PrepDevice); distortVertexBuffer = new PositionColorTexturedVertexBuffer11(((subX + 1) * (subY + 1)), RenderContext11.PrepDevice); distortVertexCount = (subX + 1) * (subY + 1); int index = 0; // Create a vertex buffer PositionColoredTextured[] verts = (PositionColoredTextured[])distortVertexBuffer.Lock(0, 0); // Lock the buffer (which will return our structs) int x1, y1; unsafe { double maxU = 0; double maxV = 0; double textureStepX = 1.0f / subX; double textureStepY = 1.0f / subY; for (y1 = 0; y1 <= subY; y1++) { double tv; for (x1 = 0; x1 <= subX; x1++) { double tu; index = y1 * (subX + 1) + x1; PixelDataRgb* pdata = fastDistort.GetRgbPixel(x1, y1); tu = (float)(pdata->blue + ((uint)pdata->red % 16) * 256) / 4095f; tv = (float)(pdata->green + ((uint)pdata->red / 16) * 256) / 4095f; //tu = (tu - .5f) * 1.7777778 + .5f; if (tu > maxU) { maxU = tu; } if (tv > maxV) { maxV = tv; } verts[index].Position = new SharpDX.Vector4(((float)x1 / subX) - .5f, (1f - ((float)y1 / subY)) - .5f, .9f, 1f); verts[index].Tu = (float)tu; verts[index].Tv = (float)tv; PixelDataRgb* pPixel = fastBlend.GetRgbPixel(x1, y1); verts[index].Color = Color.FromArgb(255, pPixel->red, pPixel->green, pPixel->blue); } } distortVertexBuffer.Unlock(); distortTriangleCount = (subX) * (subY) * 2; uint[] indexArray = (uint[])distortIndexBuffer.Lock(); index = 0; for (y1 = 0; y1 < subY; y1++) { for (x1 = 0; x1 < subX; x1++) { // First triangle in quad indexArray[index] = (uint)(y1 * (subX + 1) + x1); indexArray[index + 1] = (uint)((y1 + 1) * (subX + 1) + x1); indexArray[index + 2] = (uint)(y1 * (subX + 1) + (x1 + 1)); // Second triangle in quad indexArray[index + 3] = (uint)(y1 * (subX + 1) + (x1 + 1)); indexArray[index + 4] = (uint)((y1 + 1) * (subX + 1) + x1); indexArray[index + 5] = (uint)((y1 + 1) * (subX + 1) + (x1 + 1)); index += 6; } } this.distortIndexBuffer.Unlock(); } fastDistort.UnlockBitmap(); fastBlend.UnlockBitmap(); fastDistort.Dispose(); GC.SuppressFinalize(fastDistort); fastBlend.Dispose(); GC.SuppressFinalize(fastBlend); }
public static void Main(string[] args) { Console.WriteLine("FastBitmap (v1.2.0) Benchmarking App"); Console.WriteLine("------------------------------------------------"); // // Single-Core Passthrough Benchmarks // BenchmarkTest pt = new BenchmarkTest { Name = "Single-Core Passthrough Benchmark", IterationCount = 3 }; // System.Drawing.Bitmap Coord Benchmark pt.AddBenchmark("SysBitmap Coord", () => { using (Bitmap src = new Bitmap(Image.FromFile("image.jpg"))) using (Bitmap dst = new Bitmap(src.Width, src.Height)) { Stopwatch sw = new Stopwatch(); sw.Start(); for (int x = 0; x < dst.Width; x++) { for (int y = 0; y < dst.Height; y++) { dst.SetPixel(x, y, src.GetPixel(x, y)); } } sw.Stop(); dst.Save("SystemBitmap.jpg"); return(src.Width * src.Height / sw.Elapsed.TotalSeconds); } }); // FastBitmap Coord Benchmark pt.AddBenchmark("FastBitmap Coord", () => { using (FastBitmap src = FastBitmap.FromFile("image.jpg")) using (FastBitmap dst = new FastBitmap(src.Width, src.Height)) { Stopwatch sw = new Stopwatch(); sw.Start(); for (int x = 0; x < dst.Width; x++) { for (int y = 0; y < dst.Height; y++) { dst.Set(x, y, src.Get(x, y)); } } sw.Stop(); dst.Save("FastBitmapCoord.jpg"); return(src.Length / sw.Elapsed.TotalSeconds); } }); // FastBitmap Index Benchmark pt.AddBenchmark("FastBitmap Index", () => { using (FastBitmap src = FastBitmap.FromFile("image.jpg")) using (FastBitmap dst = new FastBitmap(src.Width, src.Height)) { Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < dst.Length; i++) { dst.Set(i, src.Get(i)); } sw.Stop(); dst.Save("FastBitmapIndex.jpg"); return(src.Length / sw.Elapsed.TotalSeconds); } }); // FastBitmap Int32 Coord Benchmark pt.AddBenchmark("FastBitmap Int32 Coord", () => { using (FastBitmap src = FastBitmap.FromFile("image.jpg")) using (FastBitmap dst = new FastBitmap(src.Width, src.Height)) { Stopwatch sw = new Stopwatch(); sw.Start(); for (int x = 0; x < dst.Width; x++) { for (int y = 0; y < dst.Height; y++) { dst.SetI(x, y, src.GetI(x, y)); } } sw.Stop(); dst.Save("FastBitmapInt32Coord.jpg"); return(src.Length / sw.Elapsed.TotalSeconds); } }); // FastBitmap Int32 Index Benchmark pt.AddBenchmark("FastBitmap Int32 Index", () => { using (FastBitmap src = FastBitmap.FromFile("image.jpg")) using (FastBitmap dst = new FastBitmap(src.Width, src.Height)) { Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < dst.Length; i++) { dst.SetI(i, src.GetI(i)); } sw.Stop(); dst.Save("FastBitmapInt32Index.jpg"); return(src.Length / sw.Elapsed.TotalSeconds); } }); // Run Passthrough pt.Run(); // Render Graph FastBitmap graph = pt.DrawGraph(); graph.Save("graph.png", ImageFormat.Png); graph.Dispose(); // Finished. Console.Write("\nAll Benchmarks Completed"); Console.Read(); }