Vultraz

GS function

Jun 10th, 2013
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.02 KB | None | 0 0
  1. surface greyscale_image(const surface &surf, bool optimize)
  2. {
  3.     if(surf == NULL)
  4.         return NULL;
  5.  
  6.     surface nsurf(make_neutral_surface(surf));
  7.     if(nsurf == NULL) {
  8.         std::cerr << "failed to make neutral surface\n";
  9.         return NULL;
  10.     }
  11.  
  12.     {
  13.         surface_lock lock(nsurf);
  14.         Uint32* beg = lock.pixels();
  15.         Uint32* end = beg + nsurf->w*surf->h;
  16.  
  17.         while(beg != end) {
  18.             Uint8 alpha = (*beg) >> 24;
  19.  
  20.             if(alpha) {
  21.                 Uint8 r, g, b;
  22.                 r = (*beg) >> 16;
  23.                 g = (*beg) >> 8;
  24.                 b = (*beg);
  25.                 //const Uint8 avg = (red+green+blue)/3;
  26.  
  27.                 // Use the correct formula for RGB to grayscale conversion.
  28.                 // Ok, this is no big deal :)
  29.                 // The correct formula being:
  30.                 // gray=0.299red+0.587green+0.114blue
  31.                 const Uint8 avg = static_cast<Uint8>((
  32.                     77  * static_cast<Uint16>(r) +
  33.                     150 * static_cast<Uint16>(g) +
  34.                     29  * static_cast<Uint16>(b)  ) / 256);
  35.  
  36.                 *beg = (alpha << 24) | (avg << 16) | (avg << 8) | avg;
  37.             }
  38.  
  39.             ++beg;
  40.         }
  41.     }
  42.  
  43.     return optimize ? create_optimized_surface(nsurf) : nsurf;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment