gd_pixelate.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include "gd.h"
  2. int gdImagePixelate(gdImagePtr im, int block_size, const unsigned int mode)
  3. {
  4. int x, y;
  5. if (block_size <= 0) {
  6. return 0;
  7. } else if (block_size == 1) {
  8. return 1;
  9. }
  10. switch (mode) {
  11. case GD_PIXELATE_UPPERLEFT:
  12. for (y = 0; y < im->sy; y += block_size) {
  13. for (x = 0; x < im->sx; x += block_size) {
  14. if (gdImageBoundsSafe(im, x, y)) {
  15. int c = gdImageGetPixel(im, x, y);
  16. gdImageFilledRectangle(im, x, y, x + block_size - 1, y + block_size - 1, c);
  17. }
  18. }
  19. }
  20. break;
  21. case GD_PIXELATE_AVERAGE:
  22. for (y = 0; y < im->sy; y += block_size) {
  23. for (x = 0; x < im->sx; x += block_size) {
  24. int a, r, g, b, c;
  25. int total;
  26. int cx, cy;
  27. a = r = g = b = c = total = 0;
  28. /* sampling */
  29. for (cy = 0; cy < block_size; cy++) {
  30. for (cx = 0; cx < block_size; cx++) {
  31. if (!gdImageBoundsSafe(im, x + cx, y + cy)) {
  32. continue;
  33. }
  34. c = gdImageGetPixel(im, x + cx, y + cy);
  35. a += gdImageAlpha(im, c);
  36. r += gdImageRed(im, c);
  37. g += gdImageGreen(im, c);
  38. b += gdImageBlue(im, c);
  39. total++;
  40. }
  41. }
  42. /* drawing */
  43. if (total > 0) {
  44. c = gdImageColorResolveAlpha(im, r / total, g / total, b / total, a / total);
  45. gdImageFilledRectangle(im, x, y, x + block_size - 1, y + block_size - 1, c);
  46. }
  47. }
  48. }
  49. break;
  50. default:
  51. return 0;
  52. }
  53. return 1;
  54. }