jacobjacobjacob
jacobjacobjacob

Reputation: 11

PPM file image not coming out as expected(no discernable shapes)

I'm a pretty beginner program, and I have to get a simple image to display in a PPM file using basic shapes in RGB.

My picture is supposed to have a green rectangle covering the lower third, a brown vertical rectangle protruding up, and a green circle on top of the brown rectangle, like a very simple tree. My code runs, but the image is scrambled. I've tried going through and removing each shape to see if those are the problem, but even with just the background, it's a jumbled mess of color. Any help would be greatly appreciated; thank you. This is my code as is right now

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

const int HEIGHT = 200;
const int WIDTH = 300;

struct RGB {
  unsigned char r, g, b;
};

void drawRect(RGB ppmImage[][WIDTH], int rectTop, int rectLeft, int rectHeight,
              int rectWidth, RGB color);

void drawCircle(RGB ppmImage[][WIDTH], int centerX, int centerY, int radius,
                RGB color);

bool writeImagePPM(RGB ppmImage[][WIDTH], const string fileName);

int main() {
  RGB ppmImage[HEIGHT][WIDTH];

  for (int row = 0; row < HEIGHT; row++)
    for (int col = 0; col < WIDTH; col++)
      ppmImage[row][col] = {0, 0, 255};

  drawRect(ppmImage, 106, 0, 67, 300, {0, 0, 255});
  drawRect(ppmImage, 130, 145, 60, 10, {139, 69, 19});

  int centerX = 145 + 10 / 2;
  int centerY = 130;
  int radius = 17;

  drawCircle(ppmImage, centerX, centerY, radius, {0, 210, 0});

  writeImagePPM(ppmImage, "imgGen.ppm");
}

void drawRect(RGB ppmImage[][WIDTH], int rectTop, int rectLeft, int rectHeight,
              int rectWidth, RGB color) {
  for (int y = rectTop; y < rectTop + rectHeight; y++)
    for (int x = rectLeft; x < rectLeft + rectWidth; x++)
      ppmImage[y][x] = color;
}

void drawCircle(RGB ppmImage[][WIDTH], int centerX, int centerY, int radius,
                RGB color) {
  for (int y = max(centerY - radius, 0); y <= min(centerY + radius, HEIGHT - 1);
       ++y) {
    for (int x = max(centerX - radius, 0);
         x <= min(centerX + radius, WIDTH - 1); ++x) {
      if ((x - centerX) * (x - centerX) + (y - centerY) * (y - centerY) <=
          radius * radius) {
        ppmImage[y][x] = color;
      }
    }
  }
}

bool writeImagePPM(RGB ppmImage[][WIDTH], const string fileName) {
  ofstream imgFile(fileName);

  if (!imgFile) {
    cout << "Error opening file: " << fileName << endl;
    return false;
  }

  imgFile << "P6\n" << WIDTH << " " << HEIGHT << "\n255\n";

  for (int row = 0; row < HEIGHT; row++) {
    for (int col = 0; col < WIDTH; col++) {
      imgFile << static_cast<int>(ppmImage[row][col].r) << ' ';
      imgFile << static_cast<int>(ppmImage[row][col].g) << ' ';
      imgFile << static_cast<int>(ppmImage[row][col].b) << ' ';
    }
    imgFile << '\n';
  }

  imgFile.close();
  return true;
}

Upvotes: 1

Views: 26

Answers (0)

Related Questions