1 // This code is in the public domain -- castanyo@yahoo.es
2
3 #include <nvcore/Debug.h>
4 #include <nvcore/Ptr.h>
5
6 #include <nvmath/Color.h>
7
8 #include <nvimage/Image.h>
9 #include <nvimage/ImageIO.h>
10
11
12 using namespace nv;
13
Image()14 Image::Image() : m_width(0), m_height(0), m_format(Format_RGB), m_data(NULL)
15 {
16 }
17
Image(const Image & img)18 Image::Image(const Image & img) : m_data(NULL)
19 {
20 allocate(img.m_width, img.m_height);
21 m_format = img.m_format;
22 memcpy(m_data, img.m_data, sizeof(Color32) * m_width * m_height);
23 }
24
~Image()25 Image::~Image()
26 {
27 free();
28 }
29
operator =(const Image & img)30 const Image & Image::operator=(const Image & img)
31 {
32 allocate(img.m_width, img.m_height);
33 m_format = img.m_format;
34 memcpy(m_data, img.m_data, sizeof(Color32) * m_width * m_height);
35 return *this;
36 }
37
38
allocate(uint w,uint h)39 void Image::allocate(uint w, uint h)
40 {
41 m_width = w;
42 m_height = h;
43 m_data = (Color32 *)realloc(m_data, w * h * sizeof(Color32));
44 }
45
load(const char * name)46 bool Image::load(const char * name)
47 {
48 free();
49
50 AutoPtr<Image> img(ImageIO::load(name));
51 if (img == NULL) {
52 return false;
53 }
54
55 swap(m_width, img->m_width);
56 swap(m_height, img->m_height);
57 swap(m_format, img->m_format);
58 swap(m_data, img->m_data);
59
60 return true;
61 }
62
wrap(void * data,uint w,uint h)63 void Image::wrap(void * data, uint w, uint h)
64 {
65 free();
66 m_data = (Color32 *)data;
67 m_width = w;
68 m_height = h;
69 }
70
unwrap()71 void Image::unwrap()
72 {
73 m_data = NULL;
74 m_width = 0;
75 m_height = 0;
76 }
77
78
free()79 void Image::free()
80 {
81 ::free(m_data);
82 m_data = NULL;
83 }
84
85
width() const86 uint Image::width() const
87 {
88 return m_width;
89 }
90
height() const91 uint Image::height() const
92 {
93 return m_height;
94 }
95
scanline(uint h) const96 const Color32 * Image::scanline(uint h) const
97 {
98 nvDebugCheck(h < m_height);
99 return m_data + h * m_width;
100 }
101
scanline(uint h)102 Color32 * Image::scanline(uint h)
103 {
104 nvDebugCheck(h < m_height);
105 return m_data + h * m_width;
106 }
107
pixels() const108 const Color32 * Image::pixels() const
109 {
110 return m_data;
111 }
112
pixels()113 Color32 * Image::pixels()
114 {
115 return m_data;
116 }
117
pixel(uint idx) const118 const Color32 & Image::pixel(uint idx) const
119 {
120 nvDebugCheck(idx < m_width * m_height);
121 return m_data[idx];
122 }
123
pixel(uint idx)124 Color32 & Image::pixel(uint idx)
125 {
126 nvDebugCheck(idx < m_width * m_height);
127 return m_data[idx];
128 }
129
130
format() const131 Image::Format Image::format() const
132 {
133 return m_format;
134 }
135
setFormat(Image::Format f)136 void Image::setFormat(Image::Format f)
137 {
138 m_format = f;
139 }
140
fill(Color32 c)141 void Image::fill(Color32 c)
142 {
143 const uint size = m_width * m_height;
144 for (uint i = 0; i < size; ++i)
145 {
146 m_data[i] = c;
147 }
148 }
149
150