public void LoadData(string path) { LoadLeetAlphabet(Path.Combine(path, "leet_alphabet.json")); LoadRatingChart(Path.Combine(path, "graph.png")); void LoadLeetAlphabet(string alphabetPath) { try { Log.Debug("Loading leet alphabet from {Path}", alphabetPath); string json = File.ReadAllText(alphabetPath, Encoding.UTF8); this.leetAlphabet = JsonConvert.DeserializeObject <Dictionary <char, string> >(json) .ToImmutableDictionary(); } catch (Exception e) { Log.Error(e, "Failed to load leet alphabet, path: {Path}", alphabetPath); throw; } } void LoadRatingChart(string ratingPath) { try { Log.Debug("Loading rating chart from {Path}", ratingPath); this.ratingChart = new Bitmap(ratingPath); } catch (Exception e) { Log.Error(e, "Failed to load rating chart, path: {Path}", ratingPath); throw; } } }
// Just forwards to Image.FromFile eating any non-critical exceptions that may result. private static Image?GetImageFromFile(string?imageFile, bool large, bool scaled = true) { Image?image = null; try { if (imageFile != null) { string?ext = Path.GetExtension(imageFile); if (ext != null && string.Equals(ext, ".ico", StringComparison.OrdinalIgnoreCase)) { //ico files support both large and small, so we respect the large flag here. using (FileStream reader = File.OpenRead(imageFile !)) { image = GetIconFromStream(reader, large, scaled); } } else if (!large) { //we only read small from non-ico files. image = Image.FromFile(imageFile !); Bitmap?b = image as Bitmap; if (DpiHelper.IsScalingRequired && scaled) { DpiHelper.ScaleBitmapLogicalToDevice(ref b); } } } } catch (Exception e) when(!ClientUtils.IsCriticalException(e)) { } return(image); }
public async Task <TimeSpan?> TryGetTimerAsync() { if (Handle == IntPtr.Zero) { return(null); } Bitmap?timerBitmap = null; try { Rectangle dimensions = captureStrategy.GetDimensions(Handle); timerBitmap = GetTopTimerAhliObsInterface(dimensions); // settings.Toggles.DefaultInterface ? GetTopTimerDefaultInterface(dimensions) : if (timerBitmap == null) { return(null); } return(await ConvertBitmapTimerToTimeSpan(timerBitmap)); } catch (Exception e) { logger.LogError(e, "Could not get timer from bitmap"); } finally { timerBitmap?.Dispose(); } return(null); }
public Task RegisterGraphics(Bitmap image) { this.map = image; this.img = Graphics.FromImage(this.map); return(Task.CompletedTask); }
private void CameraTextureWorker() { while (!IsClosing) { Task.Delay(Delay).Wait(); if (string.IsNullOrEmpty(_currentCamera)) { continue; } var cameraData = GrpcClient.GetCameraDataAsync(_currentCamera).Result; if (cameraData.Texture == null) { _statusUnstable = true; continue; } if (ByteArrayCompare(cameraData.Texture, _previousTexture)) { continue; } if (_desiredHeight == 0) { _desiredHeight = 800; } using MemoryStream ms = new(cameraData.Texture); _texture = Bitmap.DecodeToHeight(ms, (int)_desiredHeight, BitmapInterpolationMode.LowQuality); _statusUnstable = false; _previousTexture = cameraData.Texture; StringBuilder sb = new(); sb.AppendLine(cameraData.Altitude); sb.AppendLine(cameraData.Speed); Dispatcher.UIThread.InvokeAsync(() => { _desiredHeight = this.FindControl <Image>("ImgCameraTexture").DesiredSize.Height; this.FindControl <Image>("ImgCameraTexture").Source = _texture; if (_statusUnstable) { return; } var textInfo = this.FindControl <TextBlock>("TextInfo"); textInfo.Text = sb.ToString(); var window = this.FindControl <Window>("MainWindow"); window.Title = cameraData.CameraName; }); } }
private Bitmap?ResizeBitmap(Bitmap?bitmap, int requestWidth, int requestHeight) { if (bitmap == null) { return(null); } try { if (bitmap.Width > requestWidth || bitmap.Height > requestHeight) { int newWidth = requestWidth; int newHeight = requestHeight; if (bitmap.Height > bitmap.Width) { float ratio = (float)bitmap.Width / bitmap.Height; newWidth = (int)(newHeight * ratio); } else if (bitmap.Width > bitmap.Height) { float ratio = (float)bitmap.Height / bitmap.Width; newHeight = (int)(newWidth * ratio); } return(Bitmap.CreateScaledBitmap(bitmap, newWidth, newHeight, true)); } } catch (Exception ex) { Log.Error(Strings.ResizeImageError, ex); } return(bitmap); }
/// <summary> /// Initializes a new instance of the <see cref="ImageAssertException"/> class. /// </summary> /// <param name="expected">The expected <see cref="Bitmap"/>.</param> /// <param name="actual">The actual <see cref="Bitmap"/>.</param> /// <param name="message">The message.</param> /// <param name="fileName">The file or resource name.</param> public ImageAssertException(Bitmap?expected, Bitmap actual, string message, string?fileName) : base(message) { this.Expected = expected; this.Actual = actual; this.FileName = fileName; }
public override void OnPageStarted(WebView?view, string?url, Bitmap?favicon) { if (_handler?.VirtualView == null || url == WebViewHandler.AssetBaseUrl) { return; } // TODO: Sync Cookies var cancel = false; if (!GetValidUrl(url).Equals(_handler.UrlCanceled, StringComparison.OrdinalIgnoreCase)) { cancel = NavigatingCanceled(url); } _handler.UrlCanceled = null; if (cancel) { _navigationResult = WebNavigationResult.Cancel; view?.StopLoading(); } else { _navigationResult = WebNavigationResult.Success; base.OnPageStarted(view, url, favicon); } }
private IImage GetScaledImage(Bitmap?img, Stream?stream, Double imgDesiredWidth, Boolean isPreserveStream) { if (img == null) { return(GetNullImage()); } if (imgDesiredWidth.AreEqualEnough(img.Width)) { return(isPreserveStream ? new AndroidBitmap(img, stream) : new AndroidBitmap(img, null)); } var scaleRatio = imgDesiredWidth / img.Width; var width = Convert.ToInt32(img.Width * scaleRatio); var height = Convert.ToInt32(img.Height * scaleRatio); var scaledBitmap = Bitmap.CreateScaledBitmap(img, width, height, true); img.Dispose(); return(new AndroidBitmap(scaledBitmap !, null)); }
private void UpdateMenu(bool beforeMenuOpening) { List <ICommand> ChangedCommandList = PluginManager.GetChangedCommands(beforeMenuOpening); foreach (ICommand Command in ChangedCommandList) { // Update changed menus with their new state. bool MenuIsVisible = PluginManager.GetMenuIsVisible(Command); if (MenuIsVisible) { TaskbarIcon.SetMenuIsVisible(Command, true); TaskbarIcon.SetMenuHeader(Command, PluginManager.GetMenuHeader(Command)); TaskbarIcon.SetMenuIsEnabled(Command, PluginManager.GetMenuIsEnabled(Command)); Bitmap?MenuIcon = PluginManager.GetMenuIcon(Command); if (MenuIcon != null) { TaskbarIcon.SetMenuIsChecked(Command, false); TaskbarIcon.SetMenuIcon(Command, MenuIcon); } else { TaskbarIcon.SetMenuIsChecked(Command, PluginManager.GetMenuIsChecked(Command)); } } else { TaskbarIcon.SetMenuIsVisible(Command, false); } } }
public virtual async Task <TimeSpan?> TryGetTimerAsync() { Rectangle dimensions = CaptureStrategy.GetDimensions(WindowHandle); Bitmap?timer = CaptureStrategy.Capture(WindowHandle, new Rectangle(dimensions.Width / 2 - 50, 0, 100, 50)); if (timer == null) { return(null); } try { using (Bitmap resized = timer.GetResized(zoom: 2)) { OcrResult?result = await TryGetOcrResult(resized, Constants.Ocr.TIMER_HRS_MINS_SECONDS_SEPERATOR.ToString()); if (result != null) { return(TryParseTimeSpan(result)); } } } catch (Exception e) { Logger.LogError(e, e.Message); } finally { timer.Dispose(); } return(null); }
public void Allocate(int width, int height, int laneWidth) { if (_graphBitmap is not null && _graphBitmap.Width >= width && _graphBitmap.Height == height) { return; } if (_graphBitmap is not null) { _graphBitmap.Dispose(); _graphBitmap = null; } if (_graphBitmapGraphics is not null) { _graphBitmapGraphics.Dispose(); _graphBitmapGraphics = null; } _graphBitmap = new Bitmap( Math.Max(width, laneWidth * 3), height, PixelFormat.Format32bppPArgb); _graphBitmapGraphics = Graphics.FromImage(_graphBitmap); _graphBitmapGraphics.SmoothingMode = SmoothingMode.AntiAlias; // With SmoothingMode != None it is better to use PixelOffsetMode.HighQuality // e.g. to avoid shrinking rectangles, ellipses and etc. by 1 px from right bottom _graphBitmapGraphics.PixelOffsetMode = PixelOffsetMode.HighQuality; Head = 0; Count = 0; }
private void LoadFrame(int index) { if (index >= 0 && index < _images.Length) { _currentFrame = new Bitmap(_images[index].FullName); } }
private void PaintCombobox() { if (ClientRectangle.Width <= 0 || ClientRectangle.Height <= 0) { _buffer = new Bitmap(1, 1); } if (_buffer == null) { _buffer = new Bitmap(ClientRectangle.Width, ClientRectangle.Height); } using var g = Graphics.FromImage(_buffer); var rect = new Rectangle(0, 0, ClientSize.Width, ClientSize.Height); var textColor = Enabled ? ThemeProvider.Theme.Colors.LightText : ThemeProvider.Theme.Colors.DisabledText; var borderColor = ThemeProvider.Theme.Colors.GreySelection; var fillColor = ThemeProvider.Theme.Colors.LightBackground; if (Focused && TabStop) { borderColor = ThemeProvider.Theme.Colors.BlueHighlight; } using (var b = new SolidBrush(fillColor)) { g.FillRectangle(b, rect); } using (var p = new Pen(borderColor, 1)) { var modRect = new Rectangle(rect.Left, rect.Top, rect.Width - 1, rect.Height - 1); g.DrawRectangle(p, modRect); } var icon = ScrollIcons.scrollbar_arrow_hot; g.DrawImageUnscaled(icon, rect.Right - icon.Width - (ThemeProvider.Theme.Sizes.Padding / 2), (rect.Height / 2) - (icon.Height / 2)); var text = SelectedItem != null?SelectedItem.ToString() : Text; using (var b = new SolidBrush(textColor)) { var padding = 2; var modRect = new Rectangle(rect.Left + padding, rect.Top + padding, rect.Width - icon.Width - (ThemeProvider.Theme.Sizes.Padding / 2) - (padding * 2), rect.Height - (padding * 2)); var stringFormat = new StringFormat { LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Near, FormatFlags = StringFormatFlags.NoWrap, Trimming = StringTrimming.EllipsisCharacter }; g.DrawString(text, Font, b, modRect, stringFormat); } }
public void Add(string text, IViewComponent component, Bitmap?image = null) { var item = new ToolStripMenuItemFormat(this, text, component); item.ImageScaling = ToolStripItemImageScaling.None; item.Image = image; _tool.DropDownItems.Add(item); }
protected virtual void Dispose(bool disposing) { if (disposing) { _bitmap?.Dispose(); _bitmap = null; } }
protected override void Dispose(bool disposing) { if (disposing) { _buffer = null; } base.Dispose(disposing); }
public override void OnPageStarted(WebView?view, string?url, Bitmap?favicon) { if (_handler != null) { _handler.PlatformView.UpdateCanGoBackForward(_handler.VirtualView); } base.OnPageStarted(view, url, favicon); }
#pragma warning disable IDE0060, CA1801 // Remove unused parameter internal static void OnFail(Bitmap?expected, Bitmap actual, string resource) #pragma warning restore IDE0060, CA1801 // Remove unused parameter { var fullFileName = Path.Combine(Path.GetTempPath(), resource); _ = Directory.CreateDirectory(Path.GetDirectoryName(fullFileName)); actual.Save(fullFileName); TestContext.AddTestAttachment(fullFileName); }
public static Bitmap?CreateResizedBitmap(Bitmap?logicalImage, Size targetImageSize) { if (logicalImage == null) { return(null); } return(ScaleBitmapToSize(logicalImage, targetImageSize)); }
public (Bitmap PreviewImage, byte[] CompressedData) SpiralCompressImage(string imageFile) { const int previewImageSize = 512; const int rays = 64; const int rings = 32; editedImage?.Dispose(); using var original = (Bitmap)Image.FromFile(imageFile); editedImage = new Bitmap(previewImageSize, previewImageSize); FillImageWithGray(editedImage); var compressedImageData = new byte[512]; var ringDistanceInPx = original.Width / (rings * 2f); var halfSize = new Vector2(original.Width, original.Height) / 2f; var index = 0; var dataPerRay = Enumerable.Range(0, rays) .Select(ray => { var angle = MathF.Tau * ray / rays; var xyFactor = new Vector2(MathF.Cos(angle), MathF.Sin(angle)); var offsetPerRing = halfSize / rings * xyFactor; var centerOffset = xyFactor * (ringDistanceInPx * ray) / rays; return(offsetPerRing, centerOffset); }).ToArray(); for (var ring = 0; ring < rings; ring++) { for (var ray = 0; ray < rays; ray++) { var(offsetPerRing, centerOffset) = dataPerRay[ray]; var pos = halfSize + centerOffset + (offsetPerRing * ring); if (pos.X >= 0 && pos.X < original.Width && pos.Y >= 0 && pos.Y < original.Height) { var color = original.GetPixel((int)pos.X, (int)pos.Y); var brightness = color.GetBrightness(); var newX = pos.X / original.Width * editedImage.Width; var newY = pos.Y / original.Height * editedImage.Height; var colorValue = (int)(brightness * 255); var grayPixel = Color.FromArgb(colorValue, colorValue, colorValue); editedImage.SetPixel((int)newX, (int)newY, grayPixel); //todo: correct grayscale to palette (2 bits per pixel) SetPixel(compressedImageData, index, color); } index++; } } return(editedImage, compressedImageData); }
private Icon(IntPtr handle) { this.handle = handle; bitmap = Bitmap.FromHicon(handle); iconSize = new Size(bitmap.Width, bitmap.Height); bitmap = Bitmap.FromHicon(handle); iconSize = new Size(bitmap.Width, bitmap.Height); // FIXME: we need to convert the bitmap into an icon undisposable = true; }
public void Invalidate() { _bitmap?.Dispose(); using var stream = new MemoryStream(); _image.SaveAsBmp(stream); stream.Position = 0; _bitmap = new Bitmap(stream); _bounds = new Rect(0, 0, _image.Width, _image.Height); }
/// <summary> /// Releases the unmanaged resources used by an instance of the SprocketControl class and optionally releases the /// managed resources. /// </summary> /// <param name="disposing"> /// 'true' to release both managed and unmanaged resources; 'false' to release only unmanaged /// resources. /// </param> private void Dispose(bool disposing) { if (!disposing) { return; } Array.Clear(pieces, 0, pieces.Length); bmp?.Dispose(); bmp = null; }
private void LoadIcons() { DisposeIcons(); _nodeClosed = TreeViewIcons.node_closed_empty.SetColor(ThemeProvider.Theme.Colors.LightText); _nodeClosedHover = TreeViewIcons.node_closed_empty.SetColor(ThemeProvider.Theme.Colors.BlueHighlight); _nodeClosedHoverSelected = TreeViewIcons.node_closed_full.SetColor(ThemeProvider.Theme.Colors.LightText); _nodeOpen = TreeViewIcons.node_open.SetColor(ThemeProvider.Theme.Colors.LightText); _nodeOpenHover = TreeViewIcons.node_open.SetColor(ThemeProvider.Theme.Colors.BlueHighlight); _nodeOpenHoverSelected = TreeViewIcons.node_open_empty.SetColor(ThemeProvider.Theme.Colors.LightText); }
private void OnTick(Object myObject, EventArgs myEventArgs) { _client.Update(); mapImage.Visible = _client.IsConnected(); if (_client.IsConnecting()) { btConnect.Text = "Cancel"; return; } if (!_client.IsConnected()) { btConnect.Text = "Connect"; if (mapImage.Image != null) { mapImage.Image.Dispose(); mapImage.Image = null; } return; } else { btConnect.Text = "Disconnect"; } var state = _client.GetMapData(); if (state != null) { Bitmap?bm = GetBitmap(state); if (mapImage.Image != null) { mapImage.Image.Dispose(); } if (bm != null) { mapImage.Image = bm; mapImage.Width = bm.Width; mapImage.Visible = true; mapImage.Height = bm.Height; } } else { if (mapImage.Image != null) { mapImage.Image.Dispose(); mapImage.Image = null; } } }
public BoxPlacer(IScreenModule returnModule, FileSystemProject project, int pageIndex) { InitializeComponent(); _returnModule = returnModule; _project = project; _pageIndex = pageIndex; _imageCache = LoadFromFile(Path.Combine(_project.BasePath, _project.Pages[_pageIndex].GetBackgroundPath())); DoubleBuffered = true; MouseWheel += ChangeZoom; }
public void Reading() { // Reading bitmap from path try { bitmap = new Bitmap(TestFilenameIn); } catch (Exception exception) { Assert.Fail(exception.Message); } Assert.Pass(); }
protected override void OnSizeChanged(int w, int h, int oldw, int oldh) { const int minW = 1; const int minH = 1; w = w < minW ? minW : w; h = h < minH ? minH : h; base.OnSizeChanged(w, h, oldw, oldh); canvasBitmap = Bitmap.CreateBitmap(w, h, Bitmap.Config.Argb8888 !) !; drawCanvas = new Canvas(canvasBitmap); LoadPoints(); }
/// <summary> /// Create a new bitmap scaled for the device units. /// When displayed on the device, the scaled image will have same size as the original image would have when displayed at 96dpi. /// Note: this method should be called only inside an if (DpiHelper.IsScalingRequired) clause /// </summary> /// <param name="logicalBitmap">The image to scale from logical units to device units</param> public static void ScaleBitmapLogicalToDevice([NotNullIfNotNull("logicalBitmap")] ref Bitmap?logicalBitmap) { if (logicalBitmap == null) { return; } Bitmap deviceBitmap = CreateScaledBitmap(logicalBitmap); if (deviceBitmap != null) { logicalBitmap.Dispose(); logicalBitmap = deviceBitmap; } }