home *** CD-ROM | disk | FTP | other *** search
/ Big Green CD 8 / BGCD_8_Dev.iso / NEXTSTEP / Graphics / ToyViewer-2.6a / src / ImageOpr.bproj / Dither.m < prev    next >
Encoding:
Text File  |  1996-10-03  |  1.3 KB  |  80 lines

  1.  
  2. #import  "Dither.h"
  3. #import  <stdlib.h>
  4. #import  <string.h>
  5.  
  6. @implementation Dither
  7.  
  8. static const unsigned char ditherTable[4][4] = {
  9.     {  0,  8,  2, 10},
  10.     { 12,  4, 14,  6},
  11.     {  3, 11,  1,  9},
  12.     { 15,  7, 13,  5} };
  13.  
  14. - init:(int)pixellevel width:(int)width
  15. {
  16.     if ((buffer = (unsigned char *)malloc(width)) == NULL) {
  17.         [super init];
  18.         return nil;
  19.     }
  20.     lnwidth = width;
  21.     return [self reset: pixellevel];
  22. }
  23.  
  24. - reset:(int)pixellevel
  25. {
  26.     int i, v, pv, cnt;
  27.     float thresh, thstep;
  28.  
  29.     ylines = 0;
  30.     thresh = 256.0 / (pixellevel - 1) + 0.1;
  31.     thstep = (int)thresh / 17.0;
  32.     threshold[cnt = 0] = pv = 0;
  33.     for (i = 0, v = (int)thresh; i < 256; i++) {
  34.         if (i >= v) {
  35.             threshold[++cnt] = pv = v;
  36.             v = (int)((cnt + 1) * thresh);
  37.             if (v > 255) v = 255;
  38.         }
  39.         sect[i] = cnt;
  40.         grad[i] = (int)((i - pv) / thstep);
  41.     }
  42.     threshold[++cnt] = 255;
  43.     return self;
  44. }
  45.  
  46. - free
  47. {
  48.     free((void *)buffer);
  49.     [super free];
  50.     return nil;
  51. }
  52.  
  53. - (unsigned char *)buffer
  54. {
  55.     return buffer;
  56. }
  57.  
  58. - (unsigned char *)getNewLine
  59. {
  60.     int x, cc, n;
  61.     const unsigned char *yp;
  62.  
  63.     yp = ditherTable[ylines & 0x03];
  64.     for (x = 0; x < lnwidth; x++) {
  65.         cc = buffer[x];
  66.         n = sect[cc];
  67.         if (yp[x & 3] < grad[cc]) ++n;
  68.         buffer[x] = threshold[n];
  69.     }
  70.     ylines++;
  71.     return buffer;
  72. }
  73.  
  74. - (const unsigned char *)threshold
  75. {
  76.     return threshold;
  77. }
  78.  
  79. @end
  80.