image24.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include "image24.hpp"
  2. #include "image.hpp"
  3. image24::image24(unsigned short width, unsigned short height,
  4. unsigned char *buffer)
  5. {
  6. w=width;
  7. h=height;
  8. data=(unsigned char *)jmalloc(width*height*3,"image24");
  9. CONDITION(data,"unable to alloc enough memory for 24 bit image");
  10. }
  11. void image24::clear(unsigned char r, unsigned char g,
  12. unsigned char b)
  13. {
  14. int x,y;
  15. unsigned char *p=data;
  16. for (y=0;y<h;y++)
  17. {
  18. for (x=0;x<w;x++)
  19. {
  20. *(p++)=r;
  21. *(p++)=g;
  22. *(p++)=b;
  23. }
  24. }
  25. }
  26. void image24::add_error(int x, int y, int r_error, int g_error, int b_error, int error_mult)
  27. {
  28. if (x>=w || x<0 || y>=h || y<0) // check to make sure this pixel is in the image
  29. return ;
  30. unsigned char *pix=data+(y*w*3+x*3);
  31. int result;
  32. result=(int)(*pix)+r_error*error_mult/32;
  33. if (result>255)
  34. *pix=255;
  35. else if (result<0) *pix=0;
  36. else *pix=result;
  37. pix++;
  38. result=(int)(*pix)+g_error*error_mult/32;
  39. if (result>255)
  40. *pix=255;
  41. else if (result<0) *pix=0;
  42. else *pix=result;
  43. pix++;
  44. result=(int)(*pix)+b_error*error_mult/32;
  45. if (result>255)
  46. *pix=255;
  47. else if (result<0) *pix=0;
  48. else *pix=result;
  49. }
  50. image *image24::dither(palette *pal)
  51. {
  52. int i,j,closest;
  53. unsigned char r,g,b,*cur_pixel=data,ar,ag,ab;
  54. image *dest=new image(w,h);
  55. for (j=0;j<h;j++)
  56. {
  57. for (i=0;i<w;i++)
  58. {
  59. r=(*cur_pixel); cur_pixel++;
  60. g=(*cur_pixel); cur_pixel++;
  61. b=(*cur_pixel); cur_pixel++;
  62. closest=pal->find_closest(r,g,b); // find the closest match in palette
  63. dest->putpixel(i,j,closest); // set the pixel to this color
  64. pal->get(closest,ar,ag,ab); // see what the actual color we used was
  65. add_error(i+1,j,ar-r,ag-g,ab-b,8);
  66. add_error(i+2,j,ar-r,ag-g,ab-b,4);
  67. add_error(i-2,j+1,ar-r,ag-g,ab-b,2);
  68. add_error(i-1,j+1,ar-r,ag-g,ab-b,4);
  69. add_error(i,j+1,ar-r,ag-g,ab-b,8);
  70. add_error(i+1,j+1,ar-r,ag-g,ab-b,4);
  71. add_error(i+2,j+1,ar-r,ag-g,ab-b,2);
  72. }
  73. }
  74. return dest;
  75. }