-
Notifications
You must be signed in to change notification settings - Fork 1
/
ExampleImage.cpp
executable file
·125 lines (85 loc) · 2.2 KB
/
ExampleImage.cpp
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
// Image example
// Demonstrates how to load and display a TGA image
// Part of the PixelToaster Framebuffer Library - http://www.pixeltoaster.com
#include <cstdio>
#include "PixelToaster.h"
using namespace PixelToaster;
bool load( const char filename[], int & width, int & height, vector<Pixel> & pixels );
int main()
{
// load image and show it on the screen
vector<Pixel> pixels;
int width = 0;
int height = 0;
if ( !load( "ExampleImage.tga", width, height, pixels ) &&
!load( "../ExampleImage.tga", width, height, pixels ) )
{
printf( "failed to load image\n" );
return 1;
}
Display display( "Image Example", width, height );
while ( display.open() )
display.update( pixels );
return 0;
}
bool load( const char filename[], int & width, int & height, vector<Pixel> & pixels )
{
unsigned int index = 0;
vector<unsigned char> buffer;
// open file for binary reading
FILE * file = fopen( filename, "rb" );
if ( !file )
{
printf( "failed to open file\n" );
return false;
}
// read 18 byte TGA header
unsigned char header[18];
if ( !fread( header, 18, 1, file ) )
{
printf( "failed to read header\n" );
goto failure;
}
// fail if not uncompressed rgb format
if ( header[2] != 2 )
{
printf( "tga must be uncompressed rgb format\n" );
goto failure;
}
// fail if not 24 bits per pixel
if ( header[16] != 24 )
{
printf( "tga must be 24 bits per pixel\n" );
goto failure;
}
// read image pixels
width = ( header[13] << 8 ) | header[12];
height = ( header[15] << 8 ) | header[14];
buffer.resize( width * height * 3, 0 );
if ( !fread( &buffer[0], buffer.size(), 1, file ) )
{
printf( "failed to read image pixel data\n" );
goto failure;
}
fclose( file );
// convert 24 bit image pixels to floating point color
pixels.resize( width * height );
for ( int y = 0; y < height; ++y )
{
for ( int x = 0; x < width; ++x )
{
Pixel & pixel = pixels[index];
pixel.b = buffer[index*3+0] * 1.0f / 255.0f;
pixel.g = buffer[index*3+1] * 1.0f / 255.0f;
pixel.r = buffer[index*3+2] * 1.0f / 255.0f;
++index;
}
}
return true;
failure:
// onoes somebody call the whaaaambulance...
width = 0;
height = 0;
fclose( file );
return false;
}