Write two C++ functions that create or modify an existing image using the PhotoC
ID: 3730460 • Letter: W
Question
Write two C++ functions that create or modify an existing image using the PhotoChop code. (Inverted & Flip Vertically)
Invert : Set each color to be (255 – the original value):
– use RedFilter as a model.
Code:
void redShift(Image& source, int shiftAmount) {
for(int i = 0; i < IMG_HEIGHT; i++) { //for each row
for(int j = 0; j < IMG_WIDTH; j++) { //for each column
//Clamp function makes sure we don't go past 255 and wrap back around to 0
source.data[i][j].red = clamp(source.data[i][j].red + shiftAmount);
}
}
}
Flip Vertical: use rotate as a model.
Code:
void rotateRight(Image& source) {
//First make a temp image to rotate into - makes easier to avoid
// overwriting old work as we go.
Image temp;
for(int i = 0; i < IMG_HEIGHT; i++) { //for each row
for(int j = 0; j < IMG_WIDTH; j++) { //for each column
//calculate where i, j should rotate to
int newRow = j; //new row = old column
int newCol = (IMG_WIDTH - 1) - i; //new column = last column - old row
temp.data[newRow][newCol] = source.data[i][j];
}
}
//Now copy temp image over the top of the source one to replace it
source = temp;
}
Explanation / Answer
Invert :
void invert(Image& source) {
for(int i = 0; i < IMG_HEIGHT; i++) { //for each row
for(int j = 0; j < IMG_WIDTH; j++) { //for each column
//Clamp function makes sure we don't go past 255 and wrap back around to 0
source.data[i][j].red = clamp(255 - source.data[i][j],0,255);
}
}
}
int clamp(int n, int lower, int upper) {
return std::max(lower, std::min(n, upper));
}
Flip Vertical:
void flipVertical(Image& source) {
//First make a temp image to rotate into - makes easier to avoid
// overwriting old work as we go.
Image temp;
int axis = int(IMG_WIDTH/2);
for(int i = 0; i < IMG_HEIGHT; i++) { //for each row
for(int j = 0; j < IMG_WIDTH; j++) { //for each column
//calculate where i, j should rotate to
int newRow = i; //new row = old column
if(j < axis){
distfromaxis = axis-j;
int newCol = axis+distfromaxis; }
else{
distfromaxis = j-axis;
int newCol = axis - distfromaxis; }
temp.data[newRow][newCol] = source.data[i][j];
}
}
//Now copy temp image over the top of the source one to replace it
source = temp;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.