#include
#include
#include
void create_negative_image(int width, int height, int max_val, int *image_data) {
for (int i = 0; i < width * height; i++) {
image_data[i] = max_val - image_data[i]; // Create negative by subtracting pixel value from max_val
}
}
void write_pgm(const char *filename, int width, int height, int max_val, int *image_data) {
FILE *output_file = fopen(filename, "w");
if (output_file == NULL) {
printf("Error: Could not open output file\n");
exit(1);
}
fprintf(output_file, "P2\n");
fprintf(output_file, "%d %d\n", width, height);
fprintf(output_file, "%d\n", max_val);
for (int i = 0; i < width * height; i++) {
fprintf(output_file, "%d ", image_data[i]);
if ((i + 1) % width == 0) {
fprintf(output_file, "\n");
}
}
fclose(output_file);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s \n", argv[0]);
return 1;
}
FILE *file = fopen(argv[1], "r");
if (file == NULL) {
printf("Error: Could not open file %s\n", argv[1]);
return 1;
}
printf("File opened successfully: %s\n", argv[1]);
char format[3];
int width, height, max_val;
// Read PGM format
fscanf(file, "%2s", format);
if (strcmp(format, "P2") != 0) {
printf("Error: Unsupported PGM format\n");
fclose(file);
return 1;
}
printf("PGM format: %s\n", format);
// Skip over any comment lines
char ch;
while ((ch = fgetc(file)) == '#') {
while (fgetc(file) != '\n'); // Skip until end of comment line
}
ungetc(ch, file); // Push the last non-comment character back to stream
// Read width, height, and max pixel value
if (fscanf(file, "%d %d", &width, &height) != 2 || fscanf(file, "%d", &max_val) != 1) {
printf("Error: Could not read width, height, or max value\n");
fclose(file);
return 1;
}
// Check if values are reasonable
if (width <= 0 || height <= 0 || max_val <= 0) {
printf("Error: Invalid width, height, or max value\n");
fclose(file);
return 1;
}
printf("Width: %d, Height: %d, Max Value: %d\n", width, height, max_val);
// Allocate memory for image data
int *image_data = (int *)malloc(width * height * sizeof(int));
if (image_data == NULL) {
printf("Error: Memory allocation failed\n");
fclose(file);
return 1;
}
// Read pixel data
for (int i = 0; i < width * height; i++) {
if (fscanf(file, "%d", &image_data[i]) != 1) {
printf("Error: Invalid pixel data\n");
free(image_data);
fclose(file);
return 1;
}
}
fclose(file);
// Create the negative image
create_negative_image(width, height, max_val, image_data);
// Write the negative image to a new file
char output_filename[256];
snprintf(output_filename, sizeof(output_filename), "negative_%s", argv[1]);
write_pgm(output_filename, width, height, max_val, image_data);
printf("Negative image created successfully: %s\n", output_filename);
// Free the allocated memory
free(image_data);
return 0;
}