Fixed grayscale handling in main.c and tricorn.c

Now grayscale files use a color pallete and in general should be smaller.
This commit is contained in:
go38coz
2026-06-28 21:38:55 +02:00
parent cd30d4aea6
commit 03d8253206
2 changed files with 24 additions and 11 deletions
+22 -8
View File
@@ -191,13 +191,7 @@ int main(int argc, char** argv)
}
float complex complexA = (starting_point_real + starting_point_imaginary*I);
int bytesPerColour;
if (colored)
{
bytesPerColour = 3;
} else {
bytesPerColour = 1;
}
int bytesPerColour = colored ? 3 : 1;
ssize_t absolute_height = height >= 0 ? height : height * - 1;
unsigned char *tempArr = malloc(width*absolute_height*bytesPerColour);// allocate image array on the heap to support large images as the stack is usually only 8 MB big
@@ -239,6 +233,7 @@ void save_bmp(const char *filename, unsigned char *img, size_t width, ssize_t he
size_t image_size = actual_height * row_width;
size_t file_size = image_size + 54; // File size = Image Size + Headers
size_t header_offset = color ? 54 : 1078; // If colored then offset = 54 if not we add offset = 54 + 1024; 1024 Bytes for color pallete
// File header - contains information about the file
@@ -246,7 +241,7 @@ void save_bmp(const char *filename, unsigned char *img, size_t width, ssize_t he
'B', 'M', // BM - identifies file as a .bmp file
0, 0, 0, 0, // 4 bytes for file size - will be set later
0, 0, 0, 0, // Reserved
54, 0, 0, 0 // 4 bytes that specify the offset where the image array begins
0, 0, 0, 0 // 4 bytes that specify the offset where the image array begins
};
// Serialize the size into 4 bytes - (unsigned char) takes only bottom 4 bytes 1 2 3 4
@@ -255,6 +250,9 @@ void save_bmp(const char *filename, unsigned char *img, size_t width, ssize_t he
file_header[4] = (unsigned char)(file_size >> 16);
file_header[5] = (unsigned char)(file_size >> 24);
file_header[10] = (unsigned char)(header_offset);
file_header[11] = (unsigned char)(header_offset >> 8);
// Info header - contains information about the image itself
unsigned char info_header[40] = {
40, 0, 0, 0, // Size of this header
@@ -294,6 +292,22 @@ void save_bmp(const char *filename, unsigned char *img, size_t width, ssize_t he
fwrite(file_header,1,14,fptr);
fwrite(info_header,1,40,fptr);
//If image is grayscale write color dictionary to tell reader what color to visualise for each value
// Row 0 - Value 0: [R=0;B=0;G=0]
// ...
//Row i - Value i: [R=i;B=i;G=i]
if (!color) {
unsigned char palette[1024];
for (int i = 0; i < 256; i++) {
palette[i * 4 + 0] = i; // B
palette[i * 4 + 1] = i; // G
palette[i * 4 + 2] = i; // R
palette[i * 4 + 3] = 0; // Reserved (Padding)
}
fwrite(palette, 1, 1024, fptr);
}
// Save padding bytes as array so we can write from it easily to the file later
unsigned char padding_bytes[3] = {0, 0, 0};