aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/Pillow/py3/libImaging/XbmEncode.c
blob: eec4c0d846240b1dbc16bf81de85266245c2f5e5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
 * The Python Imaging Library.
 * $Id$
 *
 * encoder for Xbm data
 *
 * history:
 * 96-11-01 fl created
 *
 * Copyright (c) Fredrik Lundh 1996.
 * Copyright (c) Secret Labs AB 1997.
 *
 * See the README file for information on usage and redistribution.
 */

#include "Imaging.h"

int
ImagingXbmEncode(Imaging im, ImagingCodecState state, UINT8 *buf, int bytes) {
    const char *hex = "0123456789abcdef";

    UINT8 *ptr = buf;
    int i, n;

    if (!state->state) {
        /* 8 pixels are stored in no more than 6 bytes */
        state->bytes = 6 * (state->xsize + 7) / 8;

        state->state = 1;
    }

    if (bytes < state->bytes) {
        state->errcode = IMAGING_CODEC_MEMORY;
        return 0;
    }

    ptr = buf;

    while (bytes >= state->bytes) {
        state->shuffle(
            state->buffer,
            (UINT8 *)im->image[state->y + state->yoff] + state->xoff * im->pixelsize,
            state->xsize);

        if (state->y < state->ysize - 1) {
            /* any line but the last */
            for (n = 0; n < state->xsize; n += 8) {
                i = state->buffer[n / 8];

                *ptr++ = '0';
                *ptr++ = 'x';
                *ptr++ = hex[(i >> 4) & 15];
                *ptr++ = hex[i & 15];
                *ptr++ = ',';
                bytes -= 5;

                if (++state->count >= 79 / 5) {
                    *ptr++ = '\n';
                    bytes--;
                    state->count = 0;
                }
            }

            state->y++;

        } else {
            /* last line */
            for (n = 0; n < state->xsize; n += 8) {
                i = state->buffer[n / 8];

                *ptr++ = '0';
                *ptr++ = 'x';
                *ptr++ = hex[(i >> 4) & 15];
                *ptr++ = hex[i & 15];

                if (n < state->xsize - 8) {
                    *ptr++ = ',';
                    if (++state->count >= 79 / 5) {
                        *ptr++ = '\n';
                        bytes--;
                        state->count = 0;
                    }
                } else {
                    *ptr++ = '\n';
                }

                bytes -= 5;
            }

            state->errcode = IMAGING_CODEC_END;
            break;
        }
    }

    return ptr - buf;
}