fileformatsproject-legacy/lib/image_ppm.c

70 lines
2.6 KiB
C
Raw Permalink Normal View History

2023-12-04 23:27:48 +01:00
#include "image_ppm.h"
byte_t* image_to_ppm_text(struct image* image, off_t* size) {
if (image == NULL || image->pixels == NULL || image->width == 0 || image->height == 0) {
errno = EINVAL;
perror("Error (image_to_ppm_text)");
exit(EXIT_FAILURE);
}
string_t width = convert_number_to_string(image->width);
string_t height = convert_number_to_string(image->height);
string_t result = string_copy("P3\n");
string_concatenate(&result, width);
free(width);
string_concatenate(&result, " ");
string_concatenate(&result, height);
free(height);
string_concatenate(&result, "\n255\n");
for (size_t row = 0; row < image->height; row++) {
for (size_t column = 0; column < image->width; column++) {
struct pixel current_pixel = image->pixels[row][column];
string_t red = convert_number_to_string(current_pixel.red);
string_t green = convert_number_to_string(current_pixel.green);
string_t blue = convert_number_to_string(current_pixel.blue);
string_concatenate(&result, red);
free(red);
string_concatenate(&result, " ");
string_concatenate(&result, green);
free(green);
string_concatenate(&result, " ");
string_concatenate(&result, blue);
free(blue);
string_concatenate(&result, " ");
}
string_concatenate(&result, "\n");
}
(*size) = string_get_length(result);
return (byte_t*)result;
}
byte_t* image_to_ppm_binary(struct image* image, off_t* size) {
if (image == NULL || image->pixels == NULL || image->width == 0 || image->height == 0) {
errno = EINVAL;
perror("Error (image_to_ppm_binary)");
exit(EXIT_FAILURE);
}
size_t pixel_data_size = (image->width * image->height * 3);
string_t width = convert_number_to_string(image->width);
string_t height = convert_number_to_string(image->height);
size_t header_size = 14 + string_get_length(width) + string_get_length(height);
(*size) = header_size + pixel_data_size;
byte_t* result = (byte_t*)malloc(*size);
if (result == NULL) {
perror("Error (image_to_ppm_binary)");
exit(EXIT_FAILURE);
}
byte_t* pixel_data_start = result;
pixel_data_start += sprintf((string_t)pixel_data_start, "P6\n%s\n%s\n255\n", width, height);
free(width);
free(height);
for (size_t row = 0; row < image->height; row++) {
for (size_t column = 0; column < image->width; column++) {
struct pixel current_pixel = image->pixels[row][column];
*pixel_data_start++ = current_pixel.red;
*pixel_data_start++ = current_pixel.green;
*pixel_data_start++ = current_pixel.blue;
}
}
return result;
}