80 lines
2.0 KiB
C
80 lines
2.0 KiB
C
|
// TODO: handle big/little endian ?
|
||
|
|
||
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <stdint.h>
|
||
|
#include <unistd.h>
|
||
|
#include <fcntl.h>
|
||
|
|
||
|
#define STB_IMAGE_IMPLEMENTATION
|
||
|
#include "stb_image.h"
|
||
|
|
||
|
uint16_t engine_color_32_to_16(uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
|
||
|
uint16_t color16;
|
||
|
r = r >> 4;
|
||
|
g = g >> 4;
|
||
|
b = b >> 4;
|
||
|
a = a >> 4;
|
||
|
color16 = (a << 12) | (r << 8) | (g << 4) | b;
|
||
|
return color16;
|
||
|
}
|
||
|
|
||
|
int main(int argc, char **argv) {
|
||
|
if (argc != 3) {
|
||
|
fprintf(stderr,"Not the right number of arguments, syntax: tex <file> <outfile>\n");
|
||
|
return 1;
|
||
|
}
|
||
|
|
||
|
int width;
|
||
|
int height;
|
||
|
int components;
|
||
|
fprintf(stderr,"Loading image ...\n");
|
||
|
unsigned char * data = stbi_load(argv[1],&width,&height,&components,4);
|
||
|
if (data == NULL) {
|
||
|
fprintf(stderr,"stb_image could not decode input file.\n");
|
||
|
return 1;
|
||
|
}
|
||
|
|
||
|
int file = open(argv[2],O_WRONLY | O_CREAT | O_TRUNC,0644);
|
||
|
if (file == -1) {
|
||
|
fprintf(stderr,"Could not open output file (No permissions? Does not exist?).\n");
|
||
|
return 1;
|
||
|
}
|
||
|
|
||
|
uint16_t width2 = (uint16_t)width;
|
||
|
uint16_t height2 = (uint16_t)height;
|
||
|
if (write(file,&width2,sizeof(uint16_t)) != sizeof(uint16_t)) {
|
||
|
fprintf(stderr,"Could not write image to output file.\n");
|
||
|
}
|
||
|
|
||
|
if (write(file,&height2,sizeof(uint16_t)) != sizeof(uint16_t)) {
|
||
|
fprintf(stderr,"Could not write image to output file.\n");
|
||
|
}
|
||
|
uint16_t * outbuffer = malloc(sizeof(uint16_t) * width * height);
|
||
|
if (outbuffer == NULL) {
|
||
|
fprintf(stderr,"Could not allocate output buffer in memory.\n");
|
||
|
return 1;
|
||
|
}
|
||
|
|
||
|
fprintf(stderr,"Writing image ...\n");
|
||
|
uint32_t pixelIndex = 0;
|
||
|
while (pixelIndex < width * height * 4) {
|
||
|
uint16_t color = engine_color_32_to_16(
|
||
|
data[pixelIndex],
|
||
|
data[pixelIndex + 1],
|
||
|
data[pixelIndex + 2],
|
||
|
data[pixelIndex + 3]
|
||
|
);
|
||
|
|
||
|
outbuffer[pixelIndex / 4] = color;
|
||
|
pixelIndex += 4;
|
||
|
}
|
||
|
|
||
|
if (write(file,outbuffer,sizeof(uint16_t) * width * height) != sizeof(uint16_t) * width * height) {
|
||
|
fprintf(stderr,"Could not write image to output file.\n");
|
||
|
}
|
||
|
close(file);
|
||
|
|
||
|
return 0;
|
||
|
}
|