rgb.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include <draw.h>
  12. /*
  13. * This original version, although fast and a true inverse of
  14. * cmap2rgb, in the sense that rgb2cmap(cmap2rgb(c))
  15. * returned the original color, does a terrible job for RGB
  16. * triples that do not appear in the color map, so it has been
  17. * replaced by the much slower version below, that loops
  18. * over the color map looking for the nearest point in RGB
  19. * space. There is no visual psychology reason for that
  20. * criterion, but it's easy to implement and the results are
  21. * far more pleasing.
  22. *
  23. int
  24. rgb2cmap(int cr, int cg, int cb)
  25. {
  26. int r, g, b, v, cv;
  27. if(cr < 0)
  28. cr = 0;
  29. else if(cr > 255)
  30. cr = 255;
  31. if(cg < 0)
  32. cg = 0;
  33. else if(cg > 255)
  34. cg = 255;
  35. if(cb < 0)
  36. cb = 0;
  37. else if(cb > 255)
  38. cb = 255;
  39. r = cr>>6;
  40. g = cg>>6;
  41. b = cb>>6;
  42. cv = cr;
  43. if(cg > cv)
  44. cv = cg;
  45. if(cb > cv)
  46. cv = cb;
  47. v = (cv>>4)&3;
  48. return ((((r<<2)+v)<<4)+(((g<<2)+b+v-r)&15));
  49. }
  50. */
  51. int
  52. rgb2cmap(int cr, int cg, int cb)
  53. {
  54. int i, r, g, b, sq;
  55. uint32_t rgb;
  56. int best, bestsq;
  57. best = 0;
  58. bestsq = 0x7FFFFFFF;
  59. for(i=0; i<256; i++){
  60. rgb = cmap2rgb(i);
  61. r = (rgb>>16) & 0xFF;
  62. g = (rgb>>8) & 0xFF;
  63. b = (rgb>>0) & 0xFF;
  64. sq = (r-cr)*(r-cr)+(g-cg)*(g-cg)+(b-cb)*(b-cb);
  65. if(sq < bestsq){
  66. bestsq = sq;
  67. best = i;
  68. }
  69. }
  70. return best;
  71. }
  72. int
  73. cmap2rgb(int c)
  74. {
  75. int j, num, den, r, g, b, v, rgb;
  76. r = c>>6;
  77. v = (c>>4)&3;
  78. j = (c-v+r)&15;
  79. g = j>>2;
  80. b = j&3;
  81. den=r;
  82. if(g>den)
  83. den=g;
  84. if(b>den)
  85. den=b;
  86. if(den==0) {
  87. v *= 17;
  88. rgb = (v<<16)|(v<<8)|v;
  89. }
  90. else{
  91. num=17*(4*den+v);
  92. rgb = ((r*num/den)<<16)|((g*num/den)<<8)|(b*num/den);
  93. }
  94. return rgb;
  95. }
  96. int
  97. cmap2rgba(int c)
  98. {
  99. return (cmap2rgb(c)<<8)|0xFF;
  100. }