Task: Image noise



C#: using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;

class Program
{
    static Size size = new Size(320, 240);
    static Rectangle rectsize = new Rectangle(new Point(0, 0), size);
    static int numpixels = size.Width * size.Height;
    static int numbytes = numpixels * 3;

    static PictureBox pb;
    static BackgroundWorker worker;

    static double time = 0;
    static double frames = 0;
    static Random rand = new Random();

    static byte tmp;
    static byte white = 255;
    static byte black = 0;
    static int halfmax = int.MaxValue / 2; 

    static IEnumerable<byte> YieldVodoo()
    {
        

        for (int i = 0; i < numpixels; i++)
        {
            tmp = rand.Next() < halfmax ? black : white; 

            
            yield return tmp;
            yield return tmp;
            yield return tmp;
        }
    }

    static Image Randimg()
    {
        
        var bitmap = new Bitmap(size.Width, size.Height);
        var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);

        Marshal.Copy(
            YieldVodoo().ToArray<byte>(),
            0, 
            data.Scan0, 
            numbytes); 

        bitmap.UnlockBits(data);
        return bitmap;
    }

    [STAThread]
    static void Main()
    {
        var form = new Form();

        form.AutoSize = true;
        form.Size = new Size(0, 0);
        form.Text = "Test";

        form.FormClosed += delegate
        {
            Application.Exit();
        };

        worker = new BackgroundWorker();

        worker.DoWork += delegate
        {
            System.Threading.Thread.Sleep(500); 

            while (true)
            {
                var a = DateTime.Now;
                pb.Image = Randimg();
                var b = DateTime.Now;

                time += (b - a).TotalSeconds;
                frames += 1;

                if (frames == 30)
                {
                    Console.WriteLine("{0} frames in {1:0.000} seconds. ({2:0} FPS)", frames, time, frames / time);

                    time = 0;
                    frames = 0;
                }
            }
        };

        worker.RunWorkerAsync();

        FlowLayoutPanel flp = new FlowLayoutPanel();
        form.Controls.Add(flp);

        pb = new PictureBox();
        pb.Size = size;

        flp.AutoSize = true;
        flp.Controls.Add(pb);

        form.Show();
        Application.Run();
    }
}






VB: Imports System.Drawing.Imaging

Public Class frmSnowExercise
    Dim bRunning As Boolean = True

    Private Sub Form1_Load(ByVal sender As System.Object,
                           ByVal e As System.EventArgs) Handles MyBase.Load

        
        
        
        SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _
            Or ControlStyles.OptimizedDoubleBuffer, True)
        UpdateStyles()

        
        
        FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
        MaximizeBox = False

        
        
        
        
        Width = 320 + Size.Width - ClientSize.Width
        Height = 240 + Size.Height - ClientSize.Height

        
        
        Show()
        Activate()
        Application.DoEvents()

        
        RenderLoop()

        
        Close()

    End Sub

    Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _
            System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
        
        If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False
    End Sub

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _
            System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        
        
        e.Cancel = bRunning
        bRunning = False
    End Sub

    Private Sub RenderLoop()

        Const cfPadding As Single = 5.0F

        Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,
                            PixelFormat.Format32bppArgb)
        Dim g As Graphics = Graphics.FromImage(b)
        Dim r As New Random(Now.Millisecond)
        Dim oBMPData As BitmapData = Nothing
        Dim oPixels() As Integer = Nothing
        Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}
        Dim oStopwatch As New Stopwatch
        Dim fElapsed As Single = 0.0F
        Dim iLoops As Integer = 0
        Dim sFPS As String = "0.0 FPS"
        Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)
        Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -
                      oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)

        
        g.Clear(Color.Black)

        
        oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),
                          ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)

        
        
        
        Array.Resize(oPixels, b.Width * b.Height)
        Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,
                                             oPixels, 0, oPixels.Length)
        b.UnlockBits(oBMPData)
        
        Do
            
            
            fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F
            oStopwatch.Reset() : oStopwatch.Start()
            
            iLoops += 1
            If fElapsed >= 1.0F Then
                
                
                
                
                
                
                
                sFPS = (iLoops / fElapsed).ToString("0.0") & " FPS"
                oFPSSize = g.MeasureString(sFPS, Font)
                oFPSBG = New RectangleF(ClientSize.Width - cfPadding -
                    oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)
                
                
                fElapsed -= 1.0F
                iLoops = 0
            End If

            
            For i As Integer = 0 To oPixels.GetUpperBound(0)
                oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))
            Next

            
            oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),
                       ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)
            
            Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,
                                                 oPixels.Length)
            b.UnlockBits(oBMPData)

            
            g.FillRectangle(Brushes.Black, oFPSBG)
            
            g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)

            
            BackgroundImage = b
            Invalidate(ClientRectangle)

            
            Application.DoEvents()
        Loop While bRunning

    End Sub
End Class