XbmDecode.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * The Python Imaging Library.
  3. * $Id$
  4. *
  5. * decoder for XBM hex image data
  6. *
  7. * history:
  8. * 96-04-13 fl Created
  9. *
  10. * Copyright (c) Fredrik Lundh 1996.
  11. * Copyright (c) Secret Labs AB 1997.
  12. *
  13. * See the README file for information on usage and redistribution.
  14. */
  15. #include "Imaging.h"
  16. #define HEX(v) \
  17. ((v >= '0' && v <= '9') ? v - '0' \
  18. : (v >= 'a' && v <= 'f') ? v - 'a' + 10 \
  19. : (v >= 'A' && v <= 'F') ? v - 'A' + 10 \
  20. : 0)
  21. int
  22. ImagingXbmDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) {
  23. enum { BYTE = 1, SKIP };
  24. UINT8 *ptr;
  25. if (!state->state) {
  26. state->state = SKIP;
  27. }
  28. ptr = buf;
  29. for (;;) {
  30. if (state->state == SKIP) {
  31. /* Skip forward until next 'x' */
  32. while (bytes > 0) {
  33. if (*ptr == 'x') {
  34. break;
  35. }
  36. ptr++;
  37. bytes--;
  38. }
  39. if (bytes == 0) {
  40. return ptr - buf;
  41. }
  42. state->state = BYTE;
  43. }
  44. if (bytes < 3) {
  45. return ptr - buf;
  46. }
  47. state->buffer[state->x] = (HEX(ptr[1]) << 4) + HEX(ptr[2]);
  48. if (++state->x >= state->bytes) {
  49. /* Got a full line, unpack it */
  50. state->shuffle((UINT8 *)im->image[state->y], state->buffer, state->xsize);
  51. state->x = 0;
  52. if (++state->y >= state->ysize) {
  53. /* End of file (errcode = 0) */
  54. return -1;
  55. }
  56. }
  57. ptr += 3;
  58. bytes -= 3;
  59. state->state = SKIP;
  60. }
  61. }