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
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
/* GATE PROJECT LICENSE:
+----------------------------------------------------------------------------+
| Copyright(c) 2018-2025, Stefan Meislinger                                  |
| All rights reserved.                                                       |
|                                                                            |
| Redistribution and use in source and binary forms, with or without         |
| modification, are permitted provided that the following conditions are met:|
|                                                                            |
| 1. Redistributions of source code must retain the above copyright notice,  |
|    this list of conditions and the following disclaimer.                   |
| 2. Redistributions in binary form must reproduce the above copyright       |
|    notice, this list of conditions and the following disclaimer in the     |
|    documentation and/or other materials provided with the distribution.    |
|                                                                            |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"|
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE    |
| LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR        |
| CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF       |
| SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS   |
| INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN    |
| CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)    |
| ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF     |
| THE POSSIBILITY OF SUCH DAMAGE.                                            |
+----------------------------------------------------------------------------+
*/

#include "gate/graphics/bitmapimages.h"
#include "gate/results.h"
#include "gate/serializers.h"
#include "gate/debugging.h"
#include "gate/mathematics.h"

typedef struct gate_bmp_header_class
{
    gate_uint32_t	header_sz;
    gate_int32_t	width;
    gate_int32_t	height;
    gate_uint16_t	nplanes;
    gate_uint16_t	bitspp;
    gate_uint32_t	compress_type;
    gate_uint32_t	bmp_bytesz;
    gate_int32_t	hres;
    gate_int32_t	vres;
    gate_uint32_t	ncolors;
    gate_uint32_t	nimpcolors;
} gate_bmp_header_t;



static gate_result_t load_bitmap_as_rgba_image(
    gate_stream_t* srcstream,
    gate_bmp_header_t const* ptr_header,
    char const* palette,
    gate_size_t linelen,
    gate_rasterimage_t* image)
{
    gate_result_t result = GATE_RESULT_FAILED;
    const unsigned width = ptr_header->width < 0 ? (unsigned)(-ptr_header->width) : (unsigned)ptr_header->width;
    const unsigned height = ptr_header->height < 0 ? (unsigned)(-ptr_header->height) : (unsigned)ptr_header->height;
    gate_rasterimage_t raster;
    gate_index_t lineadd;
    gate_color_t* ptrpixel;
    gate_color_t* ptrline;
    unsigned x, y, z;
    gate_size_t lenread;
    char buffer[8192];
    char* ptr_buffer = &buffer[0];
    gate_uint8_t const* ptrbytes;
    gate_uint8_t const* ptrpal;
    gate_bool_t all_alphas_are_zero = true;

    do
    {
        gate_mem_clear(&raster, sizeof(raster));

        if (NULL == gate_rasterimage_create(&raster, GATE_IMAGE_PIXELFORMAT_RGBA, width, height, NULL))
        {
            result = GATE_RESULT_OUTOFMEMORY;
            break;
        }

        if (linelen > sizeof(buffer))
        {
            ptr_buffer = gate_mem_alloc(linelen);
            if (NULL == ptr_buffer)
            {
                result = GATE_RESULT_OUTOFMEMORY;
                break;
            }
        }

        if (ptr_header->height < 0)
        {
            ptrpixel = (gate_color_t*)gate_rasterimage_get_line_ptr(&raster, 0);
            lineadd = width;
        }
        else
        {
            ptrpixel = (gate_color_t*)gate_rasterimage_get_line_ptr(&raster, (height - 1));
            lineadd = -(gate_index_t)width;
        }

        result = GATE_RESULT_OK;
        for (y = 0; y != height; ++y)
        {

            result = gate_stream_read_block(srcstream, ptr_buffer, linelen, &lenread);
            if (GATE_FAILED(result))
            {
                break;
            }
            if (lenread < linelen)
            {
                result = GATE_RESULT_ENDOFSTREAM;
                break;
            }
            ptrline = ptrpixel;
            ptrbytes = (gate_uint8_t const*)ptr_buffer;

            for (x = 0; x < width; ++x)
            {
                switch (ptr_header->bitspp)
                {
                default:
                {
                    ptrline->b = 0;
                    ptrline->g = 0;
                    ptrline->r = 0;
                    ptrline->a = 255;
                    ++ptrline;
                    break;
                }
                case 1:
                {
                    for (z = 0; z != 8; ++z)
                    {
                        if (*ptrbytes & (gate_uint8_t)(1 << (7 - z)))
                        {
                            ptrpal = (gate_uint8_t const*)&palette[4];
                        }
                        else
                        {
                            ptrpal = (gate_uint8_t const*)&palette[0];
                        }
                        ptrline->b = ptrpal[0];
                        ptrline->g = ptrpal[1];
                        ptrline->r = ptrpal[2];
                        ptrline->a = ptrpal[3];
                        all_alphas_are_zero &= ((ptrline->a == 0) ? true : false);
                        ++ptrline;
                    }
                    ++ptrbytes;
                    x += 7;
                    break;
                }
                case 4:
                {
                    ptrpal = (gate_uint8_t const*)&palette[4 * (unsigned)(*ptrbytes >> 4)];
                    ptrline->b = ptrpal[0];
                    ptrline->g = ptrpal[1];
                    ptrline->r = ptrpal[2];
                    ptrline->a = ptrpal[3];
                    all_alphas_are_zero &= ((ptrline->a == 0) ? true : false);
                    ++ptrline;

                    ptrpal = (gate_uint8_t const*)&palette[4 * (unsigned)(*ptrbytes & 0x0f)];
                    ptrline->b = ptrpal[0];
                    ptrline->g = ptrpal[1];
                    ptrline->r = ptrpal[2];
                    ptrline->a = ptrpal[3];
                    all_alphas_are_zero &= ((ptrline->a == 0) ? true : false);
                    ++ptrline;

                    ++ptrbytes;
                    ++x;
                    break;
                }
                case 8:
                {
                    ptrpal = (gate_uint8_t const*)&palette[4 * (gate_size_t)*ptrbytes];
                    ++ptrbytes;
                    ptrline->b = ptrpal[0];
                    ptrline->g = ptrpal[1];
                    ptrline->r = ptrpal[2];
                    ptrline->a = ptrpal[3];
                    all_alphas_are_zero &= ((ptrline->a == 0) ? true : false);
                    ++ptrline;
                    break;
                }
                case 15:
                case 16:
                {
                    ptrline->b = (ptrbytes[0] & 0x1f) << 3;
                    ptrline->g = ((ptrbytes[0] >> 5) | ((ptrbytes[1] & 0x03) << 3)) << 3;
                    ptrline->r = (ptrbytes[1] & 0x7c) << 1;
                    ptrline->a = 255;
                    ++ptrline;
                    break;
                }
                case 24:
                {
                    ptrline->b = *ptrbytes++;
                    ptrline->g = *ptrbytes++;
                    ptrline->r = *ptrbytes++;
                    ptrline->a = 255;
                    ++ptrline;
                    break;
                }
                case 32:
                {
                    ptrline->b = *ptrbytes++;
                    ptrline->g = *ptrbytes++;
                    ptrline->r = *ptrbytes++;
                    ptrline->a = *ptrbytes++;
                    all_alphas_are_zero &= ((ptrline->a == 0) ? true : false);
                    ++ptrline;
                    break;
                }
                }
            } /* for(x) */

            ptrpixel += lineadd;
        } /* for(y) */

        GATE_BREAK_IF_FAILED(result);

        if (all_alphas_are_zero)
        {
            /* all alpha values are zero means, that
               the soruce stream had no alpha-values stored
               and all the reserved bits were zero.
               Therfore we just patch all alpha-values to 255
            */
            gate_size_t pixelcount = (gate_size_t)raster.width * (gate_size_t)raster.height;
            ptrpixel = (gate_color_t*)gate_rasterimage_get_line_ptr(&raster, 0);
            while (pixelcount-- != 0)
            {
                ptrpixel->a = 255;
                ++ptrpixel;
            }
        }

        /* success case, transfer local image object into output object */
        gate_mem_copy(image, &raster, sizeof(raster));
        gate_mem_clear(&raster, sizeof(raster));
        result = GATE_RESULT_OK;
    } while (0);

    if ((ptr_buffer != NULL) & (ptr_buffer != &buffer[0]))
    {
        gate_mem_dealloc(ptr_buffer);
    }
    gate_rasterimage_release(&raster);

    return result;
}


static gate_result_t load_bitmap_generic(
    gate_stream_t* srcstream,
    gate_bmp_header_t const* ptr_header,
    char const* palette,
    gate_size_t linelen,
    gate_enumint_t pixel_format,
    gate_rasterimage_t* image)
{
    gate_result_t result = GATE_RESULT_FAILED;
    const unsigned width = ptr_header->width < 0 ? (unsigned)(-ptr_header->width) : (unsigned)ptr_header->width;
    const unsigned height = ptr_header->height < 0 ? (unsigned)(-ptr_header->height) : (unsigned)ptr_header->height;
    gate_rasterimage_t raster;
    unsigned x, y, z;
    gate_size_t lenread;
    gate_color_t current_pixel;
    char buffer[8192];
    char* ptr_buffer = &buffer[0];
    gate_uint8_t const* ptrpal;

    do
    {
        gate_mem_clear(&raster, sizeof(raster));

        if (NULL == gate_rasterimage_create(&raster, pixel_format, width, height, NULL))
        {
            result = GATE_RESULT_OUTOFMEMORY;
            break;
        }

        if (linelen > sizeof(buffer))
        {
            ptr_buffer = gate_mem_alloc(linelen);
            if (NULL == ptr_buffer)
            {
                result = GATE_RESULT_OUTOFMEMORY;
                break;
            }
        }

        result = GATE_RESULT_OK;
        for (y = 0; y != height; ++y)
        {
            const unsigned dest_y = (ptr_header->height < 0) ? y : height - y - 1;
            gate_uint8_t const* ptr_line_bytes = (gate_uint8_t const*)ptr_buffer;

            result = gate_stream_read_block(srcstream, ptr_buffer, linelen, &lenread);
            if (GATE_FAILED(result))
            {
                break;
            }
            if (lenread < linelen)
            {
                result = GATE_RESULT_ENDOFSTREAM;
                break;
            }

            for (x = 0; x < width; ++x)
            {
                switch (ptr_header->bitspp)
                {
                default:
                {
                    current_pixel.b = 0;
                    current_pixel.g = 0;
                    current_pixel.r = 0;
                    current_pixel.a = 255;
                    ++ptr_line_bytes;
                    break;
                }
                case 1:
                {
                    for (z = 0; z != 8; ++z)
                    {
                        if (*ptr_line_bytes & (gate_uint8_t)(1 << (7 - z)))
                        {
                            ptrpal = (gate_uint8_t const*)&palette[4];
                        }
                        else
                        {
                            ptrpal = (gate_uint8_t const*)&palette[0];
                        }
                        current_pixel.b = ptrpal[0];
                        current_pixel.g = ptrpal[1];
                        current_pixel.r = ptrpal[2];
                        current_pixel.a = 255;

                        gate_rasterimage_set_pixel(&raster, x + z, dest_y, &current_pixel);
                    }
                    ++ptr_line_bytes;
                    x += 7;
                    break;
                }
                case 4:
                {
                    ptrpal = (gate_uint8_t const*)&palette[4 * (unsigned)(*ptr_line_bytes >> 4)];
                    current_pixel.b = ptrpal[0];
                    current_pixel.g = ptrpal[1];
                    current_pixel.r = ptrpal[2];
                    current_pixel.a = 255;
                    gate_rasterimage_set_pixel(&raster, x, dest_y, &current_pixel);
                    ++ptr_line_bytes;
                    ++x;

                    ptrpal = (gate_uint8_t const*)&palette[4 * (unsigned)(*ptr_line_bytes & 0x0f)];
                    current_pixel.b = ptrpal[0];
                    current_pixel.g = ptrpal[1];
                    current_pixel.r = ptrpal[2];
                    current_pixel.a = 255;
                    ++ptr_line_bytes;
                    break;
                }
                case 8:
                {
                    ptrpal = (gate_uint8_t const*)&palette[4 * (gate_size_t)*ptr_line_bytes];
                    current_pixel.b = ptrpal[0];
                    current_pixel.g = ptrpal[1];
                    current_pixel.r = ptrpal[2];
                    current_pixel.a = 255;
                    ++ptr_line_bytes;
                    break;
                }
                case 15:
                case 16:
                {
                    current_pixel.b = (ptr_line_bytes[0] & 0x1f) << 3;
                    current_pixel.g = ((ptr_line_bytes[0] >> 5) | ((ptr_line_bytes[1] & 0x03) << 3)) << 3;
                    current_pixel.r = (ptr_line_bytes[1] & 0x7c) << 1;
                    current_pixel.a = 255;
                    ptr_line_bytes += 2;
                    break;
                }
                case 24:
                {
                    current_pixel.b = ptr_line_bytes[0];
                    current_pixel.g = ptr_line_bytes[1];
                    current_pixel.r = ptr_line_bytes[2];
                    current_pixel.a = 255;
                    ptr_line_bytes += 3;
                    break;
                }
                case 32:
                {
                    current_pixel.b = ptr_line_bytes[0];
                    current_pixel.g = ptr_line_bytes[1];
                    current_pixel.r = ptr_line_bytes[2];
                    current_pixel.a = ptr_line_bytes[3];
                    ptr_line_bytes += 4;
                    break;
                }
                }

                gate_rasterimage_set_pixel(&raster, x, y, &current_pixel);
            } /* for(x) */
        } /* for(y) */
        GATE_BREAK_IF_FAILED(result);

        /* success case, transfer local image object into output object */
        gate_mem_copy(image, &raster, sizeof(raster));
        gate_mem_clear(&raster, sizeof(raster));
        result = GATE_RESULT_OK;
    } while (0);

    if ((ptr_buffer != NULL) & (ptr_buffer != &buffer[0]))
    {
        gate_mem_dealloc(ptr_buffer);
    }
    gate_rasterimage_release(&raster);

    return result;
}


gate_result_t gate_bitmapimage_load(gate_stream_t* srcstream, gate_rasterimage_t* image, gate_enumint_t flags)
{
    static gate_size_t const header_min_size = 54;
    char palette[1024];
    char* ptr_buffer = &palette[0];
    gate_result_t result;
    gate_uint32_t filesize;
    gate_uint32_t creatorid;
    gate_uint32_t bmpoffset;
    gate_size_t bufferused;
    gate_bmp_header_t header;

    gate_size_t linelen;
    gate_size_t remain;
    const gate_enumint_t load_pixel_format = flags & GATE_IMAGE_FLAG_DEPTHMASK;

    (void)flags;

    do
    {
        gate_rasterimage_create(image, GATE_IMAGE_PIXELFORMAT_DEFAULT, 0, 0, NULL);

        result = gate_stream_read_block(srcstream, ptr_buffer, header_min_size, &bufferused);
        if (GATE_FAILED(result))
        {
            result = GATE_RESULT_INVALIDINPUT;
            break;
        }
        if (bufferused < header_min_size || (ptr_buffer[0] != 'B') || (ptr_buffer[1] != 'M'))
        {
            result = GATE_RESULT_INVALIDHEADER;
            break;
        }
        gate_deserialize_uint32_l(&ptr_buffer[2], 4, &filesize);
        gate_deserialize_uint32_l(&ptr_buffer[6], 4, &creatorid);
        gate_deserialize_uint32_l(&ptr_buffer[10], 4, &bmpoffset);

        if (bmpoffset < header_min_size)
        {
            result = GATE_RESULT_INVALIDHEADER;
            break;
        }

        gate_deserialize_uint32_l(&ptr_buffer[14], 4, &header.header_sz);
        gate_deserialize_int32_l(&ptr_buffer[18], 4, &header.width);
        gate_deserialize_int32_l(&ptr_buffer[22], 4, &header.height);
        gate_deserialize_uint16_l(&ptr_buffer[26], 2, &header.nplanes);
        gate_deserialize_uint16_l(&ptr_buffer[28], 2, &header.bitspp);
        gate_deserialize_uint32_l(&ptr_buffer[30], 4, &header.compress_type);
        gate_deserialize_uint32_l(&ptr_buffer[34], 4, &header.bmp_bytesz);
        gate_deserialize_int32_l(&ptr_buffer[38], 4, &header.hres);
        gate_deserialize_int32_l(&ptr_buffer[42], 4, &header.vres);
        gate_deserialize_uint32_l(&ptr_buffer[46], 4, &header.ncolors);
        gate_deserialize_uint32_l(&ptr_buffer[50], 4, &header.nimpcolors);

        result = GATE_RESULT_OK;
        switch (header.compress_type)
        {
        case 0:	/* BI_RGB */
        {
            /* supported */
            break;
        }
        case 1:	/* BI_RLE8 */
        case 2:	/* BI_RLE4 */
        case 3:	/* BI_BITFIELDS */
        case 4:	/* BI_JPEG */
        case 5:	/* BI_PNG */
        default:	/* unknown */
        {
            /* unsupported encoding */
            result = GATE_RESULT_NOTSUPPORTED;
            break;
        }
        }

        GATE_BREAK_IF_FAILED(result);

        if (bmpoffset > header_min_size)
        {
            result = gate_stream_read_block(srcstream, palette, bmpoffset - header_min_size, &bufferused);
            if (GATE_FAILED(result))
            {
                result = GATE_RESULT_INVALIDHEADER;
                break;
            }
            if (bufferused < (bmpoffset - header_min_size))
            {
                result = GATE_RESULT_INVALIDINPUT;
                break;
            }
        }

        linelen = 0;

        switch (header.bitspp)
        {
        case 1:
        {
            linelen = (header.width + 7) / 8;
            break;
        }
        case 4:
        {
            linelen = (header.width + 1) / 2;
            break;
        }
        case 8:
        {
            linelen = header.width;
            break;
        }
        case 15:
        case 16:
        {
            linelen = (gate_size_t)gate_math_abs_i32(header.width) * 2;
            break;
        }
        case 24:
        {
            linelen = (gate_size_t)gate_math_abs_i32(header.width) * 3;
            break;
        }
        case 32:
        {
            linelen = (gate_size_t)gate_math_abs_i32(header.width) * 4;
            break;
        }
        }

        remain = linelen % 4;
        if (remain != 0)
        {
            linelen += 4 - remain;
        }

        switch (load_pixel_format)
        {
        case GATE_IMAGE_FLAG_DEPTH_8GRAY:	result = load_bitmap_generic(srcstream, &header, palette, linelen, GATE_IMAGE_PIXELFORMAT_GRAY8, image); break;
        case GATE_IMAGE_FLAG_DEPTH_24RGB:	result = load_bitmap_generic(srcstream, &header, palette, linelen, GATE_IMAGE_PIXELFORMAT_RGB24, image); break;
        case GATE_IMAGE_FLAG_DEPTH_15RGB:	result = load_bitmap_generic(srcstream, &header, palette, linelen, GATE_IMAGE_PIXELFORMAT_RGB555, image); break;
        case GATE_IMAGE_FLAG_DEPTH_4COL:
        case GATE_IMAGE_FLAG_DEPTH_8COL:	result = load_bitmap_generic(srcstream, &header, palette, linelen, GATE_IMAGE_PIXELFORMAT_PAL8, image); break;
        case GATE_IMAGE_FLAG_DEPTH_32RGBA:
        case GATE_IMAGE_FLAG_DEPTH_DEF:
        default:							result = load_bitmap_as_rgba_image(srcstream, &header, palette, linelen, image); break;
        }

    } while (0);

    return result;
}


static void load_bgra_line(gate_uint8_t* bmp_buffer, gate_uint8_t const* ptr_line, gate_size_t length)
{
    gate_mem_copy(bmp_buffer, ptr_line, length * 4);
}

gate_result_t gate_bitmapimage_save(gate_rasterimage_t const* image, gate_stream_t* deststream, gate_enumint_t flags)
{
    gate_result_t result;
    gate_size_t byteswritten;
    char buffer[12288];
    char* ptrbuffer = &buffer[0];

    char header[54] = GATE_INIT_EMPTY;
    gate_bmp_header_t bmp;
    const gate_size_t bmp_linelen = (gate_size_t)image->width * 4;	/* 4 bytes per pixel */
    const gate_size_t bmp_datasize = bmp_linelen * image->height;
    const gate_size_t img_linelen =
        (gate_size_t)(image->width * (unsigned)image->bits_per_pixel / 8u + (unsigned)image->line_padding);
    gate_uint8_t const* ptrline;
    gate_uint8_t* ptrbyte;

    const gate_uint32_t filesize = (gate_uint32_t)bmp_datasize + 54;
    gate_uint32_t creator = 0;
    gate_uint32_t offset = 54;

    gate_uint32_t y;
    void(*line_writer)(gate_uint8_t*, gate_uint8_t const*, gate_size_t) = NULL;

    (void)flags;

    bmp.header_sz = 40;
    bmp.width = (gate_int32_t)image->width;
    bmp.height = (gate_int32_t)image->height;
    bmp.nplanes = 1;
    bmp.bitspp = 32;
    bmp.compress_type = 0;	/* no compression */
    bmp.bmp_bytesz = (gate_uint32_t)bmp_datasize;
    bmp.hres = 0;
    bmp.vres = 0;
    bmp.ncolors = 0;
    bmp.nimpcolors = 0;

    header[0] = 'B';
    header[1] = 'M';
    gate_serialize_uint32_l(&header[2], 4, &filesize);
    gate_serialize_uint32_l(&header[6], 4, &creator);
    gate_serialize_uint32_l(&header[10], 4, &offset);

    gate_serialize_uint32_l(&header[14], 4, &bmp.header_sz);
    gate_serialize_int32_l(&header[18], 4, &bmp.width);
    gate_serialize_int32_l(&header[22], 4, &bmp.height);
    gate_serialize_uint16_l(&header[26], 2, &bmp.nplanes);
    gate_serialize_uint16_l(&header[28], 2, &bmp.bitspp);
    gate_serialize_uint32_l(&header[30], 4, &bmp.compress_type);
    gate_serialize_uint32_l(&header[34], 4, &bmp.bmp_bytesz);

    gate_serialize_int32_l(&header[38], 4, &bmp.hres);
    gate_serialize_int32_l(&header[42], 4, &bmp.vres);
    gate_serialize_uint32_l(&header[46], 4, &bmp.ncolors);
    gate_serialize_uint32_l(&header[50], 4, &bmp.nimpcolors);

    do
    {
        switch (image->pixel_format)
        {
        case GATE_IMAGE_PIXELFORMAT_RGBA:
        case GATE_IMAGE_PIXELFORMAT_RGB32:	line_writer = &gate_color_convert_bgra_from_rgba_32;	break;
        case GATE_IMAGE_PIXELFORMAT_BGRA:
        case GATE_IMAGE_PIXELFORMAT_BGR32:	line_writer = &load_bgra_line;	break;

        case GATE_IMAGE_PIXELFORMAT_RGB24:	line_writer = &gate_color_convert_bgra_from_rgb_24; break;
        case GATE_IMAGE_PIXELFORMAT_BGR24:	line_writer = &gate_color_convert_bgra_from_bgr_24; break;

        case GATE_IMAGE_PIXELFORMAT_RGB555:	line_writer = &gate_color_convert_bgra_from_rgb_15; break;
        case GATE_IMAGE_PIXELFORMAT_RGB565:	line_writer = &gate_color_convert_bgra_from_rgb_16; break;
        case GATE_IMAGE_PIXELFORMAT_ARGB4:	line_writer = &gate_color_convert_bgra_from_argb_16; break;
        case GATE_IMAGE_PIXELFORMAT_YUV2:	line_writer = &gate_color_convert_bgra_from_yuv2_16;  break;

        case GATE_IMAGE_PIXELFORMAT_PAL8:	line_writer = &gate_color_convert_bgra_from_pal_8; break;
        case GATE_IMAGE_PIXELFORMAT_GRAY8:	line_writer = &gate_color_convert_bgra_from_gray_8; break;
        default:
            break;
        }

        if (line_writer == NULL)
        {
            result = GATE_RESULT_INVALIDCONTENT;
            break;
        }

        if (bmp_linelen > sizeof(buffer))
        {
            ptrbuffer = gate_mem_alloc(bmp_linelen);
            if (ptrbuffer == NULL)
            {
                result = GATE_RESULT_OUTOFMEMORY;
                break;
            }
        }

        result = gate_stream_write_block(deststream, header, sizeof(header), &byteswritten);
        if (GATE_FAILED(result))
        {
            result = GATE_RESULT_INVALIDOUTPUT;
            break;
        }

        ptrline = (gate_uint8_t const*)gate_rasterimage_get_line_ptr(image, (image->height - 1));

        for (y = 0; y != image->height; ++y)
        {
            ptrbyte = (gate_uint8_t*)ptrbuffer;
            line_writer(ptrbyte, ptrline, image->width);

            result = gate_stream_write_block(deststream, ptrbuffer, bmp_linelen, &byteswritten);
            if (GATE_FAILED(result))
            {
                result = GATE_RESULT_INVALIDOUTPUT;
                break;
            }
            GATE_DEBUG_ASSERT(bmp_linelen == byteswritten);

            ptrline -= img_linelen;
        }
    } while (0);

    if ((ptrbuffer != &buffer[0]) && (ptrbuffer != NULL))
    {
        gate_mem_dealloc(ptrbuffer);
    }

    return result;
}