Laden...

Forenbeiträge von Pinselmeister Ingesamt 2 Beiträge

29.11.2020 - 11:39 Uhr

Danke!
Daran habe ich nicht gedacht.
Mal eben angepasst und es funktioniert

for (int y = cell.Y; y < (cell.Height + cell.Y); y++) 
{
    for (int x = cell.X; x < (cell.Width + cell.X); x++)
    {
29.11.2020 - 02:07 Uhr

Guten Abend,

in einem WinForms-Projekt lade ich eine beliebige Grafik in ein Bitmap-Objekt.
In einem bestimmten Bereich (Rectangle) möchte ich jene Farbe ermitteln und zürückgeben, die am häufigsten vorkommt.
Meine Methode gibt willkürliche Farbwerte zurück, die ich nicht erwarte und ich weiß nicht, woran es liegt

private void getCellColor(Bitmap bmp, Rectangle cell, ref Color color)
{
    if (bmp == null)
        return;

    Color[] colors = new Color[cell.Width * cell.Height];  // temporäres Array, so groß wie der Suchbereich
    int counter = 0;  // Array-Index

    for (int y = 0; y < cell.Height; y++)  // alle Farbwerte zeilenweise v.o.n.u durchgehen
    {
        for (int x = 0; x < cell.Width; x++)
        {
            colors[counter] = bmp.GetPixel(x, y);
            counter++;
        }
    }
    var result = colors.GroupBy(c => c).OrderByDescending(c => c.Count()).First();
    color = result.Key;
}

private void button1_Click(object sender, EventArgs e)
{
    if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        using (Bitmap bmp = new Bitmap(openFileDialog1.FileName))
        {
            using (Graphics g = pictureBox1.CreateGraphics())  // temporär für die Vorschau
            {
                g.DrawImage(bmp, new Point(0, 0));

                Color c = new Color();
                Rectangle r = new Rectangle(100, 100, 100, 200);

                getCellColor(bmp, r, ref c);
                this.BackColor = c;
                g.DrawRectangle(Pens.Red, r);
            }
        }
    }
}