private void timer_Tick(object sender, EventArgs e) { int sz = _currentCaptureSize; int shalf = (int)Math.Floor(_currentCaptureSize / (double)2); Bitmap screen = GetScreen(sz); using (Graphics g = Graphics.FromImage(screen)) { g.CopyFromScreen(Control.MousePosition.X - shalf, Control.MousePosition.Y - shalf, 0, 0, new System.Drawing.Size(sz, sz)); } using (Graphics g = Graphics.FromImage(_map)) { g.PixelOffsetMode = PixelOffsetMode.Half; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; g.DrawImage(screen, new Rectangle(0, 0, 100, 100), new Rectangle(0, 0, sz, sz), GraphicsUnit.Pixel); } CaptureBitmap = _map; //CaptureBitmap = (Bitmap)_map.Clone(); System.Drawing.Color drawing_Col = screen.GetPixel(sz / 2, sz / 2); PointerPixelColor = Color.FromRgb(drawing_Col.R, drawing_Col.G, drawing_Col.B); //screen.Dispose(); if (CaptureTick != null) { CaptureTick(this, new EventArgs()); } }
public void LoadColorsFromRegistry() { RegistryKey categoryKey; bool success = TryGetCategoryKey(out categoryKey); if (!success) { return; } var backgroundColorEntry = (int)categoryKey.GetValue("SelectedText Background"); var foregroundColorEntry = (int)categoryKey.GetValue("SelectedText Foreground"); System.Drawing.Color backgroundDrawingColor = ColorTranslator.FromWin32(backgroundColorEntry); System.Drawing.Color foregroundDrawingColor = ColorTranslator.FromWin32(foregroundColorEntry); BackgroundColor = Color.FromArgb(backgroundDrawingColor.A, backgroundDrawingColor.R, backgroundDrawingColor.G, backgroundDrawingColor.B); ForegroundColor = Color.FromArgb(foregroundDrawingColor.A, foregroundDrawingColor.R, foregroundDrawingColor.G, foregroundDrawingColor.B); }
/// <summary>Gets the RGB values using an image file.</summary> /// <param name="file">The image file.</param> /// <returns>The values (R)ed, (G)reen und (B)lue.</returns> public static byte[] GetRgbFromImage(string file) { int[] rgb = new int[3]; byte[] output = new byte[3]; Bitmap img = (Bitmap)Image.FromFile(file); int pixel = img.Width * img.Height; for (int x = 0, maxX = img.Width; x < maxX; x++) { for (int y = 0, maxY = img.Height; y < maxY; y++) { System.Drawing.Color color = img.GetPixel(x, y); rgb[0] += color.R; rgb[1] += color.G; rgb[2] += color.B; } } for (int i = 0; i < rgb.Length; i++) { output[i] = Convert.ToByte(rgb[i] / pixel); } return(output); }
public string FillImageColor(System.Drawing.Color c) { var image = Path.GetTempFileName(); DrawFilledRectangle(3840, 2160, new SolidBrush(c)).Save(image, ImageFormat.Jpeg); return(image); }
/// <summary>Blends the specified colors together.</summary> /// <param name="color">Color to blend onto the background color.</param> /// <param name="backColor">Color to blend the other color onto.</param> /// <param name="amount">How much of <paramref name="color"/> to keep, /// “on top of” <paramref name="backColor"/>.</param> /// <returns>The blended colors.</returns> public static System.Drawing.Color Blend(this System.Drawing.Color color, System.Drawing.Color backColor, double amount) { byte r = (byte)((color.R * amount) + backColor.R * (1 - amount)); byte g = (byte)((color.G * amount) + backColor.G * (1 - amount)); byte b = (byte)((color.B * amount) + backColor.B * (1 - amount)); return(System.Drawing.Color.FromArgb(r, g, b)); }
public void SetColor(System.Drawing.Color color) { double[] hsla = ColorHelper.RgbaToHsla(color.ConvertDrawingColorToMediaColor()); hsla = ColorHelper.ExpandDoublesToHSLAValues(hsla); HueSliderValue = (int)hsla[0]; SaturationSliderValue = (int)hsla[1]; LuminositySliderValue = (int)hsla[2]; AlphaSliderValue = (int)hsla[3]; }
public static bool CompareColor(int oldCi, int newCi, byte colorLimit) { System.Drawing.Color oldC = System.Drawing.Color.FromArgb(oldCi); System.Drawing.Color newC = System.Drawing.Color.FromArgb(newCi); return(CompareColor(oldC.A, newC.A, colorLimit) && CompareColor(oldC.R, newC.R, colorLimit) && CompareColor(oldC.G, newC.G, colorLimit) && CompareColor(oldC.B, newC.B, colorLimit)); }
/// <summary> /// Converts from a .NET Standard-compatible System.Drawing.Color to /// a WPF-compatible System.Windows.Media.Color /// </summary> static public System.Windows.Media.Color ConvertColor(System.Drawing.Color color) { return(new System.Windows.Media.Color() { R = color.R, G = color.G, B = color.B, A = color.A }); }
public void SetBoxColors() { System.Drawing.Color colorMin = manipulation.Hue(MinimumHue); System.Drawing.Color colorMax = manipulation.Hue(MaximumHue); Color brushColorMin = Color.FromArgb(colorMin.A, colorMin.R, colorMin.G, colorMin.B); Color brushColorMax = Color.FromArgb(colorMax.A, colorMax.R, colorMax.G, colorMax.B); Brush brushMin = new SolidColorBrush(brushColorMin); Brush brushMax = new SolidColorBrush(brushColorMax); UserControl.rectangleColorMin.Fill = brushMin; UserControl.rectangleColorMax.Fill = brushMax; }
public static Bitmap DrawAudio(DmoMp3Decoder decoder, System.Drawing.Color background) { var bmp = new Bitmap(60, 35); var bytesPerSample = decoder.WaveFormat.BitsPerSample / 8 * decoder.WaveFormat.Channels; var samplesPerPixel = 128; long startPosition = 0; var BORDER_WIDTH = 1; var width = bmp.Width - 2 * BORDER_WIDTH; var height = bmp.Height - 2 * BORDER_WIDTH; using (var g = Graphics.FromImage(bmp)) { g.Clear(background); var color = (Color)Application.Current.Resources["DarkColor"]; var pen1 = new Pen(System.Drawing.Color.FromArgb(204, color.R, color.G, color.B)); var waveData1 = new byte[samplesPerPixel * bytesPerSample]; decoder.Position = startPosition + width * bytesPerSample * samplesPerPixel; for (float x = 0; x < width; x++) { short low = 0; short high = 0; var bytesRead1 = decoder.Read(waveData1, 0, samplesPerPixel * bytesPerSample); if (bytesRead1 == 0) { break; } for (var n = 0; n < bytesRead1; n += 2) { var sample = BitConverter.ToInt16(waveData1, n); if (sample < low) { low = sample; } if (sample > high) { high = sample; } } var lowPercent = ((float)low - short.MinValue) / ushort.MaxValue; var highPercent = ((float)high - short.MinValue) / ushort.MaxValue; var lowValue = height * lowPercent; var highValue = height * highPercent; g.DrawLine(pen1, x, lowValue, x, highValue); } } return(bmp); }
public MainWindow() { InitializeComponent(); _started = true; _thread = new Thread(RunCapture); _thread.Start(); _threadS = new Thread(SerialPortConnect); _threadS.Start(); _dominantColor = System.Drawing.Color.FromArgb(0, 0, 0); SleepForColorInput = 100; SleepSendingSerial = 100; }
public override FScheme.Value Evaluate(FSharpList <FScheme.Value> args) { storedPath = ((FScheme.Value.String)args[0]).Item; double xDiv = ((FScheme.Value.Number)args[1]).Item; double yDiv = ((FScheme.Value.Number)args[2]).Item; FSharpList <FScheme.Value> result = FSharpList <FScheme.Value> .Empty; if (File.Exists(storedPath)) { try { using (var bmp = new Bitmap(storedPath)) { DispatchOnUIThread(delegate { // how to convert a bitmap to an imagesource http://blog.laranjee.com/how-to-convert-winforms-bitmap-to-wpf-imagesource/ // TODO - watch out for memory leaks using system.drawing.bitmaps in managed code, see here http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/4e213af5-d546-4cc1-a8f0-462720e5fcde // need to call Dispose manually somewhere, or perhaps use a WPF native structure instead of bitmap? var hbitmap = bmp.GetHbitmap(); var imageSource = Imaging.CreateBitmapSourceFromHBitmap(hbitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(bmp.Width, bmp.Height)); image1.Source = imageSource; }); // Do some processing for (int y = 0; y < yDiv; y++) { for (int x = 0; x < xDiv; x++) { System.Drawing.Color pixelColor = bmp.GetPixel(x * (int)(bmp.Width / xDiv), y * (int)(bmp.Height / yDiv)); result = FSharpList <FScheme.Value> .Cons(FScheme.Value.NewContainer(pixelColor), result); } } } } catch (Exception e) { DynamoLogger.Instance.Log(e.ToString()); } return(FScheme.Value.NewList(result)); } else { return(FScheme.Value.NewList(FSharpList <FScheme.Value> .Empty)); } }
private void ContrastColor(System.Drawing.Color color) { var d = 0; var a = 1 - (0.299 * color.R + 0.587 * color.G + 0.114 * color.B) / 255; if (a < 0.5) { label.Foreground = Brushes.Black; } else { label.Foreground = Brushes.White; } }
private void Eyedropper_OnMouseMove(object sender, MouseEventArgs e) { if (!_mDown) { return; } var elem = sender as UIElement; var mPos = e.GetPosition(elem); Point sPos = elem.PointToScreen(mPos); Debug.WriteLine(sPos.ToString()); Bitmap cap = Extensions.ScrCap(new Rectangle((int)sPos.X, (int)sPos.Y, 1, 1)); System.Drawing.Color capCol = cap.GetPixel(0, 0); Color = Color.FromArgb(capCol.A, capCol.R, capCol.G, capCol.B); }
public Tuple <System.Drawing.Color, System.Drawing.Color> GenerateColourPairFromHash() { //split the hash by the ':' character string[] strarray = lblFingerPrint.Content.ToString().Split(':'); //create a byte array byte[] byteArray = new byte[8]; int posInByteArray = 0; foreach (string str in strarray.TakeWhile(str => posInByteArray != 8)) { //assign byte array with 8 byte values after converting them from base 16 byteArray[posInByteArray++] = Convert.ToByte(str, 16); } //create 2 two colours with the byte array, the alpha is constant 255 as there were issues with very low alpha levels System.Drawing.Color leftColour = System.Drawing.Color.FromArgb(255, byteArray[0], byteArray[1], byteArray[2]); System.Drawing.Color rightColour = System.Drawing.Color.FromArgb(255, byteArray[3], byteArray[4], byteArray[5]); return(new Tuple <System.Drawing.Color, System.Drawing.Color>(leftColour, rightColour)); }
public void RunCapture() { int count = 0; long avg = 0; double primaryScreenWidth = SystemParameters.PrimaryScreenWidth; double primaryScreenHeight = SystemParameters.PrimaryScreenHeight; int topMargin = 30; int bottomMargin = 60; while (_started) { var stopwatch = new Stopwatch(); stopwatch.Start(); var bitmapSource = CaptureScreenshot.CaptureBmp(new Rect(0, topMargin, primaryScreenWidth, primaryScreenHeight - bottomMargin)); System.Drawing.Color color = CalculateAverageColor(bitmapSource); lock (_setColor) { _dominantColor = color; } Dispatcher.BeginInvoke(new Action(CaptureScreenShot), null); stopwatch.Stop(); avg += stopwatch.ElapsedMilliseconds; count++; //Speed test and cleanup if (count > 10) { Dispatcher.BeginInvoke(new Action(() => CaptureTime.Text = string.Format("Time: {0} [{1}x{2}]", (avg / count), primaryScreenWidth, primaryScreenHeight))).Wait(); avg = 0; count = 0; GC.Collect(); } Thread.Sleep(SleepForColorInput); } }
/// <summary> /// Gets or sets the get known color dictionary. Key is the KnownColor name, Value contains the ARGB int Color value. /// </summary> /// <value>get known color dictionary.</value> public static Dictionary <int, string> GetKnownColorDictionary() { var knownColorDictionary = new Dictionary <int, string>(); List <string> knownColorName = Enum.GetNames(typeof(KnownColor)).ToList(); foreach (string name in knownColorName) { //cast the colorName into a KnownColor var knownColor = (KnownColor)Enum.Parse(typeof(KnownColor), name); System.Drawing.Color drawingColor = System.Drawing.Color.FromKnownColor(knownColor); //check if the knownColor variable is a System color if (knownColor > KnownColor.Transparent) { int argbValue = drawingColor.ToArgb(); if (!knownColorDictionary.ContainsKey(argbValue)) { knownColorDictionary.Add(argbValue, name); } } } knownColorName = null; return(knownColorDictionary); }
private static Point GetRotatedPositionDeprecated(float rotationAngleToRealign, Point currentPosition, int displayWidth, int displayHeight) { System.Drawing.Color bkColor = System.Drawing.Color.FromArgb(200, 200, 200); var bitmap = new Bitmap(displayWidth, displayHeight); var g = Graphics.FromImage(bitmap); g.Clear(bkColor); g.Dispose(); var positionColor = System.Drawing.Color.DarkViolet; bitmap.SetPixel((int)currentPosition.X, (int)currentPosition.Y, positionColor); bitmap.SetPixel((int)currentPosition.X + 1, (int)currentPosition.Y, positionColor); bitmap.SetPixel((int)currentPosition.X - 1, (int)currentPosition.Y, positionColor); bitmap.SetPixel((int)currentPosition.X, (int)currentPosition.Y + 1, positionColor); bitmap.SetPixel((int)currentPosition.X, (int)currentPosition.Y - 1, positionColor); bitmap.SetPixel((int)currentPosition.X + 1, (int)currentPosition.Y + 1, positionColor); bitmap.SetPixel((int)currentPosition.X - 1, (int)currentPosition.Y - 1, positionColor); var rotatedBitmap = MainProcessor.RotateImg(bitmap, rotationAngleToRealign, bkColor); for (var y = 0; y < displayHeight; y++) { for (var x = 0; x < displayWidth; x++) { var color = rotatedBitmap.GetPixel(x, y); if (color.R == positionColor.R && color.G == positionColor.G && color.B == positionColor.B) { return(new Point(x, y)); } } } throw new Exception("Could not find rotated position"); }
public static Color Convert(System.Drawing.Color value) { return(Color.FromArgb(255, value.R, value.G, value.B)); }
private void BtnExportXaml_Click(object sender, EventArgs e) { Image pic = il32.Images[pnlPictures.SelectedIndex]; string newName = $"Image"; newName = newName + ".Xaml"; try { string xamlOutputText = string.Empty; string xamlOutput = string.Empty; previewTarget = new System.Windows.Controls.Canvas { Background = Brushes.Transparent }; Rectangle rectangle = null; Bitmap bitmap = new Bitmap(pic); previewTarget.Height = bitmap.Height; previewTarget.Width = bitmap.Width; for (int y = 0; y < bitmap.Height; ++y) { for (int x = 0; x < bitmap.Width; ++x) { System.Drawing.Color pixel = bitmap.GetPixel(x, y); rectangle = new Rectangle { Fill = new SolidColorBrush(Color.FromArgb(pixel.A, pixel.R, pixel.G, pixel.B)) }; rectangle.Height = rectangle.Width = 1.0; rectangle.SetValue(System.Windows.Controls.Canvas.LeftProperty, (double)x); rectangle.SetValue(System.Windows.Controls.Canvas.TopProperty, (double)y); rectangle.SnapsToDevicePixels = true; previewTarget.Children.Add(rectangle); Application.DoEvents(); } } Application.DoEvents(); XmlWriterSettings settings = new XmlWriterSettings { Indent = true, IndentChars = "\t", ConformanceLevel = ConformanceLevel.Fragment }; StringBuilder output = new StringBuilder(); XamlWriter.Save(previewTarget, XmlWriter.Create(output, settings)); xamlOutputText = output.ToString(); saveFileDialog1.Filter = "Xaml Files(*.Xaml)|*.Xaml|All files (*.*)|*.*"; saveFileDialog1.FilterIndex = 1; saveFileDialog1.RestoreDirectory = true; saveFileDialog1.FileName = newName; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { TextWriter writeFile = new StreamWriter(saveFileDialog1.FileName); writeFile.Write(xamlOutputText); writeFile.Flush(); writeFile.Close(); writeFile = null; } } catch { MessageBox.Show("Failed to save Xaml to Xaml format.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } MessageBox.Show("Xaml file saved to " + newName, "Xaml Saved", MessageBoxButtons.OK, MessageBoxIcon.Information); }
public static IntPtr ToWin32Color(this System.Drawing.Color color) { return((IntPtr)(UInt32)ColorTranslator.ToWin32(color)); }
private Color mediaColorToDrawing(System.Drawing.Color c) { return(Color.FromArgb(c.A, c.R, c.G, c.B)); }
public static Color ToAvalonColor(this System.Drawing.Color value) { return(Color.FromArgb(value.A, value.R, value.G, value.B)); }
private string ParseRgbaFunctionString(string value) { if (string.IsNullOrEmpty(value)) return "Invalid rgba function format."; var match = _rgbaRegex.Match(value); if (!match.Success) return "Invalid rgba function format."; var channels = new byte[4]; for (var i = 0; i < 4; i++) { var str = match.Groups[i + 1].Value; if (!TryParseParameter(str, out channels[i])) return string.Format("Invalid parameter '{0}'.", str); } _drawingColor = System.Drawing.Color.FromArgb(channels[3], channels[0], channels[1], channels[2]); Colour = Color.FromArgb(channels[3], channels[0], channels[1], channels[2]); return null; }
public static Color ToColor(this System.Drawing.Color color) { return(Color.FromArgb(color.A, color.R, color.G, color.B)); }
public static Bitmap GetThemedBitmap(Bitmap source, System.Drawing.Color backgroundColor, bool isHighContrast) { return(GetThemedBitmap(source, (uint)ColorTranslator.ToWin32(backgroundColor), isHighContrast)); }
/// <summary> /// Knowns the color to int. /// </summary> /// <param name="knownColor">Color of the known.</param> /// <returns></returns> public static Int32 KnownColorToInt(KnownColor knownColor) { System.Drawing.Color drawingColor = System.Drawing.Color.FromKnownColor(knownColor); return(ColorToInt(drawingColor)); }
public static Span ToSpan(this RichText.RichText richtext) { var span = new Span(); string plaintext = richtext.Text; foreach (RichString part in richtext.GetFormattedParts()) { var run = new Run(plaintext.Substring(part.Offset, part.Length)); span.Inlines.Add(run); if ((part.Style.FontStyle & FontStyle.Bold) != 0) { run.FontWeight = FontWeights.Bold; } if ((part.Style.FontStyle & FontStyle.Italic) != 0) { run.FontStyle = FontStyles.Italic; } if ((part.Style.FontStyle & FontStyle.Underline) != 0) { run.TextDecorations.Add(TextDecorations.Underline); } if ((part.Style.FontStyle & FontStyle.Strikeout) != 0) { run.TextDecorations.Add(TextDecorations.Strikethrough); } System.Drawing.Color color = part.Style.ForegroundColor; if (!color.IsEmpty) { run.Foreground = new SolidColorBrush(Color.FromArgb(color.A, color.R, color.G, color.B)); } color = part.Style.BackgroundColor; if (!color.IsEmpty) { run.Background = new SolidColorBrush(Color.FromArgb(color.A, color.R, color.G, color.B)); } color = part.Style.EffectColor; Pen pen = null; if (!color.IsEmpty) { pen = new Pen { Brush = new SolidColorBrush(Color.FromArgb(color.A, color.R, color.G, color.B)) } } ; switch (part.Style.Effect) { case TextStyle.EffectStyle.None: break; case TextStyle.EffectStyle.StraightUnderline: run.TextDecorations.Add(new TextDecoration { Location = TextDecorationLocation.Underline, Pen = pen }); break; case TextStyle.EffectStyle.WeavyUnderline: run.TextDecorations.Add(new TextDecoration { Location = TextDecorationLocation.Underline, Pen = pen }); break; case TextStyle.EffectStyle.StrikeOut: run.TextDecorations.Add(new TextDecoration { Location = TextDecorationLocation.Strikethrough, Pen = pen }); break; default: throw new InvalidOperationException("Effect."); } } return(span); } #endregion }
public static Color ToMediaColor(this System.Drawing.Color color) => Color.FromArgb(color.A, color.R, color.G, color.B);
protected System.Drawing.Color GetColor(Color color, double? opacity) { if (color == null) { return System.Drawing.Color.FromArgb(0, 0, 0, 0); } System.Drawing.Color result = new System.Drawing.Color(); result = System.Drawing.Color.FromArgb((int)(_opacity * 255), color.R, color.G, color.B); return result; }
static Color ConvertColor(System.Drawing.Color C) { return(Color.FromArgb(C.A, C.R, C.G, C.B)); }
private static System.Drawing.Bitmap makeTransparentBitmap(System.Drawing.Image image, System.Drawing.Color mask) { try { var bmp = new System.Drawing.Bitmap(image.Width, image.Height); using (var g = System.Drawing.Graphics.FromImage(bmp)) { var imgAttribute = new ImageAttributes(); imgAttribute.SetColorKey(mask, mask); g.DrawImage(image, new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel, imgAttribute); } return(bmp); } catch (Exception ex) { PNStatic.LogException(ex); return(null); } }