5c9b2425ab13bf0363a0fc2f4b4ff202fdafd11a
[winnie] / src / pixmap.cc
1 #include <stdio.h>
2 #include <string.h>
3 #include <errno.h>
4 #include "pixmap.h"
5
6 Pixmap::Pixmap()
7 {
8         width = height = 0;
9         pixels = 0;
10 }
11
12 Pixmap::~Pixmap()
13 {
14         if(pixels) {
15                 delete [] pixels;
16         }
17 }
18
19 int Pixmap::get_width() const
20 {
21         return width;
22 }
23
24 int Pixmap::get_height() const
25 {
26         return height;
27 }
28
29 Rect Pixmap::get_rect() const
30 {
31         Rect rect = {0, 0, width, height};
32         return rect;
33 }
34
35 bool Pixmap::set_image(int x, int y, unsigned char *pix)
36 {
37         delete [] pixels;
38
39         pixels = new unsigned char[x * y * 4];
40         width = x;
41         height = y;
42
43         if(pix) {
44                 memcpy(pixels, pix, x * y * 4);
45         }
46         return true;
47 }
48
49 const unsigned char *Pixmap::get_image() const
50 {
51         return pixels;
52 }
53
54 unsigned char *Pixmap::get_image()
55 {
56         return pixels;
57 }
58
59 bool Pixmap::load(const char *fname)
60 {
61         return false;   // TODO
62 }
63
64 bool Pixmap::save(const char *fname) const
65 {
66         if(!pixels) {
67                 return false;
68         }
69
70         FILE *fp = fopen(fname, "wb");
71         if(!fp) {
72                 fprintf(stderr, "failed to save pixmap: %s: %s\n", fname, strerror(errno));
73                 return false;
74         }
75
76         fprintf(fp, "P6\n%d %d\n255\n", width, height);
77
78         for(int i=0; i<width * height; i++) {
79                 fputc(pixels[i * 4], fp);
80                 fputc(pixels[i * 4 + 1], fp);
81                 fputc(pixels[i * 4 + 2], fp);
82         }
83
84         fclose(fp);
85         return true;
86 }