-
Notifications
You must be signed in to change notification settings - Fork 0
/
Image.cpp
96 lines (85 loc) · 1.81 KB
/
Image.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
#include "Image.h"
#include "rgb.h"
#include <string>
#include <fstream>
Image::Image(const Image &_orig){
nx=_orig.getWidth();
ny=_orig.getHeight();
data=new rgb*[nx];
for(int i=0;i<nx;i++){
data[i]=new rgb[ny];
for(int j=0;j<ny;j++)
data[i][j]=_orig.getRGB(i,j);
}
}
Image::Image(int _width,int _height,const rgb &background)
:nx(_width),ny(_height){
data=new rgb*[nx];
for(int i=0;i<nx;i++){
data[i]=new rgb[ny];
for(int j=0;j<ny;j++)
data[i][j]=background;
}
}
Image::Image(std::string filename){
std::ifstream in(filename,std::ios::in|std::ios::binary);
char ch,type;
in.get(ch);
in.get(type);
int num;
in>>nx>>ny>>num;
data=new rgb*[nx];
for(int i=0;i<nx;i++)
data[i]=new rgb[ny];
in.get(ch);
char r,g,b;
for(int i=ny-1;i>0;--i)
for(int j=0;j<nx;j++){
in.get(r);
in.get(g);
in.get(b);
data[j][i]=rgb((double)((unsigned char)r/255.0),(double)((unsigned char)g/255.0),(double)((unsigned char)b/255.0));
}
in.close();
}
Image::~Image(){
for(int i=0;i<nx;i++)
delete[] data[i];
delete[] data;
}
rgb Image::getRGB(int i,int j)const{
return data[i][j];
}
bool Image::setRGB(int i,int j,const rgb &_color){
if((i<0)||(i>=nx))
return false;
if((j<0)||(j>=ny))
return false;
data[i][j]=_color;
return true;
}
int Image::getWidth()const{
return nx;
}
int Image::getHeight()const{
return ny;
}
bool Image::writePPM(std::ofstream &out){
out<<"P6"<<std::endl;
out<<nx<<' '<<ny<<std::endl;
out<<"255"<<std::endl;
unsigned int r,g,b;
for(int i=0;i<ny;i++)
for(int j=0;j<nx;j++){
r=(unsigned int)(256*data[j][i].getR());
g=(unsigned int)(256*data[j][i].getG());
b=(unsigned int)(256*data[j][i].getB());
r=r<256?r:255;
g=g<256?g:255;
b=b<256?b:255;
out.put((unsigned char)r);
out.put((unsigned char)g);
out.put((unsigned char)b);
}
return true;
}