Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the random pixel color not so random in my C# application?

I set up a code to randomly cover a bitmap 2 different colors, 7 out of 10 times the color would be blue, and 3 out of 10 times, the color would be green. However, when it's done it looks very un-random, like it decided to put 7 blue pixels a few times, then 3 green pixels a few times and so on.
Example:
alt text My code is:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FourEx
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Bitmap bmp = new Bitmap(canvas.Image);
            System.Drawing.Imaging.BitmapData bmpdata = bmp.LockBits(new Rectangle(0, 0, 800, 600), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            unsafe
            {
                int tempy = 0;
                while (tempy < 600)
                {
                    byte* row = (byte*)bmpdata.Scan0 + (tempy * bmpdata.Stride);
                    for (int x = 0; x <= 800; x++)
                    {
                        Random rand = new Random();
                        if (rand.Next(1,10) <= 7)
                        {
                            row[x * 4] = 255;
                        }
                        else
                        {
                            row[(x * 4) + 1] = 255;
                        }
                    }
                    tempy++;
                }
            }
            bmp.UnlockBits(bmpdata);
            canvas.Image = bmp;
        }
    }
}

If you need an additional information, let me know.

like image 700
GunnarJ Avatar asked Dec 21 '22 20:12

GunnarJ


1 Answers

move this line:

Random rand = new Random(); 

to the outermost scope. If you create these quickly many will get the same time seed (due to precision of the clock) and will generate the same 'random' sequence. Plus, you only really need one Random instance...

private void Form1_Load(object sender, EventArgs e) 
{ 
    Bitmap bmp = new Bitmap(canvas.Image); 
    System.Drawing.Imaging.BitmapData bmpdata = bmp.LockBits(new Rectangle(0, 0, 800, 600), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb); 

    Random rand = new Random(); 

    unsafe 
    { 
    // ....
like image 85
Mitch Wheat Avatar answered Dec 28 '22 11:12

Mitch Wheat