public Result Save(string path, bool overwrite, bool compress = false) // compress is ignored. { var returnResult = new Result(string.Format("Saving heightmap to \"{0}\".", path), false); logger.Info("Saving heightmap to \"{0}\"", path); var heightmapBitmap = new Bitmap(map.Terrain.TileSize.X + 1, map.Terrain.TileSize.Y + 1); for (var Y = 0; Y <= map.Terrain.TileSize.Y; Y++) { for (var X = 0; X <= map.Terrain.TileSize.X; X++) { heightmapBitmap.SetPixel(X, Y, ColorTranslator.FromOle(ColorUtil.OsRgb(Convert.ToInt32(map.Terrain.Vertices[X, Y].Height), map.Terrain.Vertices[X, Y].Height, map.Terrain.Vertices[X, Y].Height))); } } var subResult = BitmapUtil.SaveBitmap(path, overwrite, heightmapBitmap); if (!subResult.Success) { returnResult.ProblemAdd(subResult.Problem); } return(returnResult); }
public unsafe void Mutate(MutateHandler mutateHandler) { BitmapUtil.InvokeAsLocked(this.impl_, bmpData => { var ptr = (byte *)bmpData.Scan0; void GetHandler(int x, int y, out byte r, out byte g, out byte b, out byte a) { var index = 4 * (y * bmpData.Width + x); b = ptr[index]; g = ptr[index + 1]; r = ptr[index + 2]; a = ptr[index + 3]; } void SetHandler(int x, int y, byte r, byte g, byte b, byte a) { var index = 4 * (y * bmpData.Width + x); ptr[index] = b; ptr[index + 1] = g; ptr[index + 2] = r; ptr[index + 3] = a; } mutateHandler(GetHandler, SetHandler); }); }
public async Task TestDecodeDimensions_TestJpegs() { var file1 = await StorageFile.GetFileFromApplicationUriAsync( new Uri("ms-appx:///Assets/ImageUtils/jpegs/1.jpeg")); using (var stream = await file1.OpenReadAsync()) { Tuple<int, int> dimensions = await BitmapUtil.DecodeDimensionsAsync(stream.AsStream()); Assert.AreEqual(new Tuple<int, int>(240, 181), dimensions); } var file2 = await StorageFile.GetFileFromApplicationUriAsync( new Uri("ms-appx:///Assets/ImageUtils/jpegs/2.jpeg")); using (var stream = await file2.OpenReadAsync()) { Tuple<int, int> dimensions = await BitmapUtil.DecodeDimensionsAsync(stream.AsStream()); Assert.AreEqual(new Tuple<int, int>(240, 93), dimensions); } var file3 = await StorageFile.GetFileFromApplicationUriAsync( new Uri("ms-appx:///Assets/ImageUtils/jpegs/3.jpeg")); using (var stream = await file3.OpenReadAsync()) { Tuple<int, int> dimensions = await BitmapUtil.DecodeDimensionsAsync(stream.AsStream()); Assert.AreEqual(new Tuple<int, int>(240, 240), dimensions); } }
private static void LoadImages(Appearance appearance, string butlerFolder, Bitmap defaultImage) { if (appearance == null) { return; } try { appearance.Icon = new Icon(Path.Combine(butlerFolder, appearance.IconFile)); } catch (Exception) { appearance.Icon = Resources.jenkins_icon; } try { string file = Path.Combine(butlerFolder, appearance.ImageFile); appearance.Image = BitmapUtil.ToBitmapSource(LoadImage(file)); } catch (Exception) { appearance.Image = BitmapUtil.ToBitmapSource(defaultImage); } if (appearance.MessageStyle.BackgroundFile != null) { LoadImage(appearance.MessageStyle, butlerFolder); } }
private static Bitmap TakeScreenShot(Activity activity) { try { View view = activity.Window.DecorView; if (view != null) { //view.DrawingCacheEnabled = true; //view.BuildDrawingCache(); //Bitmap b1 = view.DrawingCache; Bitmap b1 = BitmapUtil.LoadBitmapFromView(view); Rect frame = new Rect(); activity.Window.DecorView.GetWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.Top; Display display = activity.WindowManager.DefaultDisplay; Point size = new Point(); display.GetSize(size); int width = size.X; int height = size.Y; Bitmap b = Bitmap.CreateBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight); //view.DestroyDrawingCache(); return(b); } return(null); } catch (Exception e) { Console.WriteLine(e); return(null); } }
/// <summary> /// Runs WFC with overlapping model in a thread creating a <see cref="Bitmap"/> that is based /// on the specified input. /// </summary> /// <param name="inputBitmap">The input image.</param> /// <param name="options">The overlapping model options.</param> /// <param name="seed">The seed for the random number generator.</param> /// <returns>The resulting image or <c>null</c>.</returns> private static Task <Bitmap> RunWfcAsync(Bitmap inputBitmap, OverlappingWfcOptions options, int seed) { return(Task.Run(() => { var inputColors = BitmapUtil.FetchColorsAsArgb(inputBitmap); // Create WFC overlapping model instance with the created array, the options and the seed // for the random number generator. var wfc = new OverlappingWfc <int>(inputColors, options, seed); // Run the WFC algorithm. The result is an Array2D with the result pixels/colors. Return value // is null, if the WFC failed to create a solution without contradictions. In this case one // should change the settings or try again with a different seed for the random number generator. var result = wfc.Run(); // Failed... if (result == null) { return null; } // Success: extract pixels/colors and put them into an image. var resultBitmap = BitmapUtil.CreateFromArgbColors(result); return resultBitmap; })); }
public unsafe void Access(IImage.AccessHandler accessHandler) { var palette = this.impl_.Palette.Entries; BitmapUtil.InvokeAsLocked(this.impl_, bmpData => { var ptr = (byte *)bmpData.Scan0; void GetHandler(int x, int y, out byte r, out byte g, out byte b, out byte a) { var index = y * bmpData.Width + x; var colorIndex = ptr[index]; var color = palette[colorIndex]; r = color.R; g = color.G; b = color.B; a = color.A; } accessHandler(GetHandler); }); }
private Paragraph GeneratePreview(LinkedList <object> list) { // 富文本预览 Paragraph paragraph = new Paragraph(); foreach (var a in list) { if (a is TextColor textColor) { paragraph.Inlines.Add(new Run() { Text = textColor.Text.Replace("\\n", "\n"), Foreground = new SolidColorBrush(GetKeyColor(textColor.Key)) }); } else if (a is TextIcon textIcon) { var image = GetKeyImage(textIcon.Key); if (image != null) { paragraph.Inlines.Add(new InlineUIContainer(new Image { Source = BitmapUtil.BitmapToBitmapImage(image, 20, 20), Width = 20, Height = 20 })); } } } return(paragraph); }
private void CreateImageFields(World world) { for (var i = 0; i < world.size; i++) { for (var j = 0; j < world.size; j++) { switch (world.GetField(i, j).type) { case FieldType.DIRT: world.GetField(i, j).image.Source = BitmapUtil.BitmapToImageSource(resources.GetObject("Dirt") as Bitmap); break; case FieldType.STONE: world.GetField(i, j).image.Source = BitmapUtil.BitmapToImageSource(resources.GetObject("Stone") as Bitmap); break; case FieldType.EXIT: world.GetField(i, j).image.Source = BitmapUtil.BitmapToImageSource(resources.GetObject("Exit") as Bitmap); break; } WorldMap.Children.Add(world.GetField(i, j).image); Canvas.SetTop(world.GetField(i, j).image, j * gridSize); Canvas.SetLeft(world.GetField(i, j).image, i * gridSize); } } }
/// <summary> /// ListBox添加item /// </summary> /// <returns></returns> public List <ListBoxItem> ListLbi() { var listBoxItem = new List <ListBoxItem>(); var list = new FileUtil().GetLocalImagesUrl(); var bUtil = new BitmapUtil(); var wf = new WPFSupportFormat(); for (int i = 0; i < list.Count; i++) { var lbi = new ListBoxItem(); lbi.HorizontalContentAlignment = HorizontalAlignment.Center; var sp = new StackPanel(); var image = new Image(); image.Stretch = Stretch.UniformToFill; image.Source = wf.ChangeBitmapToImageSource(bUtil.Zip(new System.Drawing.Bitmap(list[i]), 320, 180));//new BitmapImage(new Uri(list[i])); var lable = new Label(); lable.Content = i + 1; sp.Children.Add(image); sp.Children.Add(lable); lbi.Content = sp; listBoxItem.Add(lbi); } return(listBoxItem.ToList()); }
public Result Save(string path, bool overwrite, bool compress = false) // compress is ignored. { var returnResult = new Result(string.Format("Saving minimap to \"{0}\".", path), false); logger.Info("Saving minimap to \"{0}\"", path); var minimapBitmap = new Bitmap(map.Terrain.TileSize.X, map.Terrain.TileSize.Y); var texture = new clsMinimapTexture(new XYInt(map.Terrain.TileSize.X, map.Terrain.TileSize.Y)); map.MinimapTextureFill(texture); for (var y = 0; y <= map.Terrain.TileSize.Y - 1; y++) { for (var x = 0; x <= map.Terrain.TileSize.X - 1; x++) { minimapBitmap.SetPixel(x, y, ColorTranslator.FromOle( ColorUtil.OsRgb( MathUtil.ClampSng(Convert.ToSingle(texture.get_Pixels(x, y).Red * 255.0F), 0.0F, 255.0F).ToInt(), (MathUtil.ClampSng(Convert.ToSingle(texture.get_Pixels(x, y).Green * 255.0F), 0.0F, 255.0F)).ToInt(), (MathUtil.ClampSng(Convert.ToSingle(texture.get_Pixels(x, y).Blue * 255.0F), 0.0F, 255.0F)).ToInt() ))); } } var subResult = BitmapUtil.SaveBitmap(path, overwrite, minimapBitmap); if (!subResult.Success) { returnResult.ProblemAdd(subResult.Problem); } return(returnResult); }
public SimpleResult Load_Image(string Path) { var ReturnResult = new SimpleResult(); ReturnResult.Success = false; ReturnResult.Problem = ""; Bitmap HeightmapBitmap = null; var Result = new SimpleResult(); Result = BitmapUtil.LoadBitmap(Path, ref HeightmapBitmap); if (!Result.Success) { ReturnResult.Problem = Result.Problem; return(ReturnResult); } Blank(HeightmapBitmap.Height, HeightmapBitmap.Width); var X = 0; var Y = 0; for (Y = 0; Y <= HeightmapBitmap.Height - 1; Y++) { for (X = 0; X <= HeightmapBitmap.Width - 1; X++) { var with_1 = HeightmapBitmap.GetPixel(X, Y); HeightData.Height[Y, X] = Convert.ToInt32(((with_1.R) + with_1.G + with_1.B) / (3.0D * HeightScale)); } } ReturnResult.Success = true; return(ReturnResult); }
/// <summary> /// Calculates the text size /// </summary> /// <returns></returns> private static SizeD CalcTextSize(string text, Font font, StringFormat format) { SizeF tmpSize; AARectangle boundingBox; if (String.IsNullOrEmpty(text) || font == null) { return(SizeD.Empty); } var bText = new SolidBrush(Color.Black); // Find the approximation of the text size using (var g = Graphics.FromImage(new Bitmap(100, 100))) { tmpSize = g.MeasureString(text, font); } // now create a minimal bmp with approx size using (var scanBMP = new Bitmap((int)tmpSize.Width, (int)tmpSize.Height)) { using (var gScan = Graphics.FromImage(scanBMP)) { gScan.Clear(Color.White); gScan.DrawString(text, font, bText, 1, 1, format); bText.Dispose(); } boundingBox = BitmapUtil.BoundingBox(scanBMP, Color.White); } return(boundingBox.Size); }
public Bitmap ToBitmap() { Bitmap bitmap = new Bitmap(this.Width, this.Height); if (this.Type.IsIndexed()) { Color[] colorPalette = BitmapUtil.PaletteToColors(this.Palette, this.Format); byte[] linear = BitmapUtil.Unswizzle(this.Data, (this.Width * this.Type.GetIndexBits()) / 8, this.Height, (this.Width * this.Type.GetIndexBits()) / 8, this.Height); int indexBits = this.Type.GetIndexBits(); for (int y = 0; y < this.Height; y++) { for (int x = 0; x < this.Width; x++) { int dataIndex = y * this.Width + x; int index = 0; if (indexBits == 4) { index = (linear[dataIndex / 2] >> ((dataIndex & 1) * 4)) & 0xF; } else { index = linear[dataIndex] & 0xFF; } bitmap.SetPixel(x, y, colorPalette[index]); } } } else { if (this.Format == PixelFormat.DXT1A || this.Format == PixelFormat.DXT1A_EXT) { BitmapUtil.DecompressDxt1(this.Width, this.Height, this.Format == PixelFormat.DXT1A_EXT, this.Data, bitmap); } else { int pixelSize = this.Format.GetSize(); byte[] linear = BitmapUtil.Unswizzle(this.Data, this.Width * pixelSize, this.Height, this.Width * pixelSize, this.Height); for (int y = 0; y < this.Height; y++) { for (int x = 0; x < this.Width; x++) { int pixel = 0; for (int j = 0; j < pixelSize; j++) { pixel |= (linear[(y * this.Width + x) * pixelSize + j] & 0xFF) << (j * 8); } bitmap.SetPixel(x, y, this.Format.ToColor(pixel)); } } } } return(bitmap); }
public void ReloadImage() { if (_filePath == "") { return; } Graphic = BitmapUtil.GetImage(_filePath); }
internal void SetErrorMessage(string errorMessage, string errorLogFile) { UpdateAppearance(ButlerFactory.Sad, null); this.sourceUrl = errorLogFile; this.messageText = errorMessage; this.appearance.Image = BitmapUtil.ToBitmapSource(Resources.sad); this.hasNews = true; }
/// <summary> /// Runs the WFC algorithm. /// </summary> /// <returns></returns> public async Task RunWfc() { if (_Tiles.Count == 0 || _Neighbors.Count == 0) { return; } groupBoxSettings.Enabled = false; var stopwatch = new Stopwatch(); var retries = 0; Array2D <int> result = null; try { stopwatch.Start(); while (retries < numericUpDownRetries.Value && result == null) { Logger.LogNeutral($"Attempt #{retries + 1} ..."); result = await RunWfcAsync(); if (result == null) { numericUpDownSeed.Value = MakeRandomSeed(); } retries++; } stopwatch.Stop(); } catch (Exception ex) { stopwatch.Stop(); MessageBox.Show(ex.ToString(), "Unexpected error", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (result != null) { var oldImage = pixelartBoxOutput.Image; pixelartBoxOutput.Image = BitmapUtil.CreateFromArgbColors(result); if (oldImage != null) { oldImage.Dispose(); } Logger.LogSuccess($"Succeeded in {stopwatch.ElapsedMilliseconds}ms after {retries} attempt(s)"); } else { Logger.LogFailure($"Failed in {stopwatch.ElapsedMilliseconds}ms after {retries} attempt(s)"); } groupBoxSettings.Enabled = true; }
private void Window_MouseDown(object sender, MouseButtonEventArgs e) { var mouse = MouseUtil.GetMousePosition(); var compensatedX = mouse.X - SystemInformation.VirtualScreen.Left; // Compensate for potential negative position on multi-monitor var compensatedY = mouse.Y - SystemInformation.VirtualScreen.Top; // Compensate for potential negative position on multi-monitor var rgb = BitmapUtil.PixelToRgb(FreezeFrame.Instance.BitmapSource, compensatedX, compensatedY); _vm.RefreshFromRgb(rgb); ColorPicked?.Invoke(this, EventArgs.Empty); Close(); }
private void EncryptAndValidate(string message) { List <int> diffs = _encryptor.Encrypt(message); Bitmap result = _converter.ToBitmap(diffs); Assert.True((result.Width * result.Height) >= diffs.Count); BitmapUtil.Iterate(result, diffs, (point, diff) => { Color color = result.GetPixel(point.X, point.Y); Assert.Equal(diff, Convert.ToInt32(color.R)); }); }
public void CombineBitmaps() { string srcfile1 = TestUtil.GetTestFile("bitmap\\combine1.png"); string srcfile2 = TestUtil.GetTestFile("bitmap\\combine2.png"); Bitmap src = (Bitmap)Image.FromFile(srcfile1); Bitmap dest = (Bitmap)Image.FromFile(srcfile2); Rectangle srcRect = new Rectangle(10, 10, 160, 180); Rectangle destRect = new Rectangle(50, 30, 160, 180); BitmapUtil.MergeBitmap(dest, destRect, src, srcRect); TestUtil.CheckBitmapsBase(dest, "bitmap\\combineout"); }
private void ChangeBackgroundImage(Bitmap bitmap) { var value = true; dispatcher.Invoke(new Action(() => { value = IsVisible; }), DispatcherPriority.Normal); if (!value) { return; } dispatcher.BeginInvoke(new Action(() => { Background = new ImageBrush(BitmapUtil.BitmapToBitmapImage(bitmap, 800, 450)); }), DispatcherPriority.Normal); Thread.Sleep(5000); }
public CanvasViewModel() { BackGround = BitmapUtil.GetImage(@"C:\Users\ud\source\repos\MTGTool\MTGTool\bin\Debug\Image\UI\背景.png"); MessageWindow = BitmapUtil.GetImage(@"C:\Users\ud\source\repos\MTGTool\MTGTool\bin\Debug\Image\UI\メッセージウインドウ.png"); _currentMsg = Repository.Get(typeof(SelectedMessage)) as SelectedMessage; _currentMsg.OnChange.Subscribe(_ => { RaisePropertyChanged(nameof(Name)); RaisePropertyChanged(nameof(Message)); RaisePropertyChanged(nameof(Character)); }); ObjectGroups = Repository.Get(typeof(ObjectGroupList)) as ObjectGroupList; VisibleMessage = Repository.Get(typeof(VisibleMessageWindow)) as VisibleMessageWindow; }
public void LightenBitmap() { Bitmap src = (Bitmap)Image.FromFile(TestUtil.GetTestFile("bitmap\\lighten_src.png")); BitmapUtil.LightenBitmap(src, 0.5); TestUtil.CheckBitmapsBase(src, "bitmap\\lighten1"); src = (Bitmap)Image.FromFile(TestUtil.GetTestFile("bitmap\\lighten_src.png")); BitmapUtil.LightenBitmap(src, 0.2); TestUtil.CheckBitmapsBase(src, "bitmap\\lighten2"); src = (Bitmap)Image.FromFile(TestUtil.GetTestFile("bitmap\\lighten_src.png")); BitmapUtil.LightenBitmap(src, 0.8); TestUtil.CheckBitmapsBase(src, "bitmap\\lighten3"); }
/// <summary> /// Includes given bitmap in the bitmap count. The bitmap is /// included only if doing so does not violate configured limit. /// </summary> /// <param name="bitmap">To include in the count.</param> /// <returns> /// true if and only if bitmap is successfully included in /// the count. /// </returns> public bool Increase(SoftwareBitmap bitmap) { lock (_bitmapGate) { uint bitmapSize = BitmapUtil.GetSizeInBytes(bitmap); if (_count >= _maxCount || _size + bitmapSize > _maxSize) { return(false); } _count++; _size += bitmapSize; return(true); } }
/// <summary> /// Excludes given bitmap from the count. /// </summary> /// <param name="bitmap"> /// To be excluded from the count. /// </param> public void Decrease(SoftwareBitmap bitmap) { lock (_bitmapGate) { uint bitmapSize = BitmapUtil.GetSizeInBytes(bitmap); Preconditions.CheckArgument(_count > 0, "No bitmaps registered."); Preconditions.CheckArgument( bitmapSize <= _size, "Bitmap size bigger than the total registered size: %d, %d", bitmapSize, _size); _size -= bitmapSize; _count--; } }
private void ApplySettings(Workspace workspace) { workspace.Initialize(); this.timer.Interval = TimeSpan.FromSeconds(workspace.Business.TimerInterval); this.notifyIcon.Icon = workspace.Butler.Icon; this.Title = workspace.Butler.DisplayName; this.Icon = BitmapUtil.ToBitmapSource(workspace.Butler.Icon.ToBitmap()); System.Windows.Forms.ToolStripItem callTheButlerMenuItem = this.notifyIcon.ContextMenuStrip.Items[CallTheButlerMenuItem]; callTheButlerMenuItem.Text = string.Format(Properties.Resources.NotifyIcon_CallTheButler, workspace.Butler.Nickname); callTheButlerMenuItem.Visible = true; }
public SpinnerWheel() { _canvasView = new SKCanvasView(); _canvasView.PaintSurface += OnCanvasViewPaintSurface; Content = _canvasView; _canvasView.EnableTouchEvents = true; _canvasView.Touch += CanvasViewOnTouch; // commands GoLeftCommand = new Command(() => { var rotationAnimation = new Animation(rotationAngle => { RotationAngle = rotationAngle; _canvasView.InvalidateSurface(); }, RotationAngle, RotationAngle + 60.0d, Easing.CubicInOut); rotationAnimation.Commit(this, "LeftRotationAnimation", 1000 / 60, 300); }); GoRightCommand = new Command(() => { var rotationAnimation = new Animation(rotationAngle => { RotationAngle = rotationAngle; _canvasView.InvalidateSurface(); }, RotationAngle, RotationAngle - 60.0d, Easing.CubicInOut); rotationAnimation.Commit(this, "RightRotationAnimation", 1000 / 60, 300); }); // Default selected index _selectedItemIndex = 1; // Load mandatory cat pictures _bitmaps = new List <SKBitmap>(); foreach (var resourceName in new List <string> { "img_a.png", "img_b.png", "img_d.png" }) { var relativePath = $"Assets.{resourceName}"; _bitmaps.Add(BitmapUtil.LoadBitmapFromResource(relativePath)); } }
private static void LoadImage(MessageStyle style, string butlerFolder) { string file = Path.Combine(butlerFolder, style.BackgroundFile); BitmapSource image = BitmapUtil.ToBitmapSource(LoadImage(file)); style.Background = new ImageBrush(image); if (style.Width == 0) { style.Width = image.Width; } if (style.Height == 0) { style.Height = image.Height; } }
public async Task TestDecodeDimensions_TestProgressiveJpegs() { var file1 = await StorageFile.GetFileFromApplicationUriAsync( new Uri("ms-appx:///Assets/ImageUtils/jpegs/1prog.jpeg")); using (var stream = await file1.OpenReadAsync()) { Tuple<int, int> dimensions = await BitmapUtil.DecodeDimensionsAsync(stream.AsStream()); Assert.AreEqual(new Tuple<int, int>(981, 657), dimensions); } var file2 = await StorageFile.GetFileFromApplicationUriAsync( new Uri("ms-appx:///Assets/ImageUtils/jpegs/2prog.jpeg")); using (var stream = await file2.OpenReadAsync()) { Tuple<int, int> dimensions = await BitmapUtil.DecodeDimensionsAsync(stream.AsStream()); Assert.AreEqual(new Tuple<int, int>(800, 531), dimensions); } }
public async Task TestDecodeDimensions_TestAnimatedGifs() { var file1 = await StorageFile.GetFileFromApplicationUriAsync( new Uri("ms-appx:///Assets/ImageUtils/animatedgifs/1.gif")); using (var stream = await file1.OpenReadAsync()) { Tuple<int, int> dimensions = await BitmapUtil.DecodeDimensionsAsync(stream.AsStream()); Assert.AreEqual(new Tuple<int, int>(500, 500), dimensions); } var file2 = await StorageFile.GetFileFromApplicationUriAsync( new Uri("ms-appx:///Assets/ImageUtils/animatedgifs/2.gif")); using (var stream = await file2.OpenReadAsync()) { Tuple<int, int> dimensions = await BitmapUtil.DecodeDimensionsAsync(stream.AsStream()); Assert.AreEqual(new Tuple<int, int>(550, 400), dimensions); } }