title: Faster contrast algorithm for a bitmap
body: <p>I have a tool with trackbar slider controls used to adjust an image's brightness, contrast, gamma, etc.</p>
  
  <p>I am trying to get real-time updates to my image while the user drags the slider.  The brightness and gamma algorithms are an acceptable speed (around 170ms).  But the contrast algorithm is about 380ms.</p>
  
  <p>Basically my form is a tool window with sliders.  Each time the image is updated, it sends an event to the parent which redraws the new image.  The tool window keeps the original unmodified image locked in memory so I always have access to the bytes of it.  So basically I do this each time the ValueChanged event for a slider (such as the Contrast slider) is changed.</p>
  
  <ul>
  <li>LockBits of the working (destination) bitmap as Format24bppRgb (original bitmap is in Format32bppPArgb)</li>
  <li>Marshal.Copy the bits to a byte[] array</li>
  <li>Check which operation I'm doing (which slider was chosen)</li>
  <li>Use the following code for Contrast:</li>
  </ul>
  
  <p>Code:</p>
  
  <pre><code>double newValue = 0;
  double c = (100.0 + contrast) / 100.0;
  
  c *= c;
  
  for (int i = 0; i &lt; sourcePixels.Length; i++)
  {
      newValue = sourcePixels[i];
  
      newValue /= 255.0;
      newValue -= 0.5;
      newValue *= c;
      newValue += 0.5;
      newValue *= 255;
  
      if (newValue &lt; 0)
          newValue = 0;
      if (newValue &gt; 255)
          newValue = 255;
  
      destPixels[i] = (byte)newValue;
  }
  </code></pre>
  
  <p>I read once about using integer instead of floating point values to increase the speed of contrast, but I couldn't find that article again.</p>
  
  <p>I tried using unsafe code (pointers) but actually noticed a speed decrease.  I assume it was because the code was using nested for loops to iterate x and y instead of a single loop.</p>