Skip to content

Instantly share code, notes, and snippets.

@NSG650
Created April 6, 2022 13:45
Show Gist options
  • Save NSG650/2477b5e8b1684b4e205b5871a8513e47 to your computer and use it in GitHub Desktop.
Save NSG650/2477b5e8b1684b4e205b5871a8513e47 to your computer and use it in GitHub Desktop.
// depends on stb_image and stb_image_write
// build using cc dither.c -o dither -lm
#include <stdio.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
int main(int argc, char **argv) {
if (argc != 4) {
printf("[!] Invalid usage of arguments\n[!] Tool should be used like this\n");
printf("[!] %s /path/to/image.ext /path/to/output.png <mono/color>\n", argv[0]);
return -1;
}
char *file_path = argv[1];
int32_t x, y, n;
uint32_t *data = (uint32_t*)stbi_load(file_path, &x, &y, &n, 4);
uint32_t *out = (uint32_t*)malloc(x * y * 4);
if(!data) {
printf("[!] Failed to load image\n");
return -1;
}
const uint8_t map[16][16] = {
{ 0, 191, 48, 239, 12, 203, 60, 251, 3, 194, 51, 242, 15, 206, 63, 254 },
{ 127, 64, 175, 112, 139, 76, 187, 124, 130, 67, 178, 115, 142, 79, 190, 127 },
{ 32, 223, 16, 207, 44, 235, 28, 219, 35, 226, 19, 210, 47, 238, 31, 222 },
{ 159, 96, 143, 80, 171, 108, 155, 92, 162, 99, 146, 83, 174, 111, 158, 95 },
{ 8, 199, 56, 247, 4, 195, 52, 243, 11, 202, 59, 250, 7, 198, 55, 246 },
{ 135, 72, 183, 120, 131, 68, 179, 116, 138, 75, 186, 123, 134, 71, 182, 119 },
{ 40, 231, 24, 215, 36, 227, 20, 211, 43, 234, 27, 218, 39, 230, 23, 214 },
{ 167, 104, 151, 88, 163, 100, 147, 84, 170, 107, 154, 91, 166, 103, 150, 87 },
{ 2, 193, 50, 241, 14, 205, 62, 253, 1, 192, 49, 240, 13, 204, 61, 252 },
{ 129, 66, 177, 114, 141, 78, 189, 126, 128, 65, 176, 113, 140, 77, 188, 125 },
{ 34, 225, 18, 209, 46, 237, 30, 221, 33, 224, 17, 208, 45, 236, 29, 220 },
{ 161, 98, 145, 82, 173, 110, 157, 94, 160, 97, 144, 81, 172, 109, 156, 93 },
{ 10, 201, 58, 249, 6, 197, 54, 245, 9, 200, 57, 248, 5, 196, 53, 244 },
{ 137, 74, 185, 122, 133, 70, 181, 118, 136, 73, 184, 121, 132, 69, 180, 117 },
{ 42, 233, 26, 217, 38, 229, 22, 213, 41, 232, 25, 216, 37, 228, 21, 212 },
{ 169, 106, 153, 90, 165, 102, 149, 86, 168, 105, 152, 89, 164, 101, 148, 85 }
};
int32_t row, col;
for (size_t i = 0; i < x; i++) {
col = i % 16;
for (size_t j = 0; j < y; j++) {
row = j % 16;
uint8_t *rgba = (uint8_t *)&data[j * x + i];
uint8_t new[4];
new[3] = 0xff;
new[0] = rgba[0] > map[col][row] ? 0xff : 0x00;
if(strcmp(argv[3], "mono")) { // if you know how strcmp works
new[1] = rgba[1] > map[col][row] ? 0xff : 0x00;
new[2] = rgba[2] > map[col][row] ? 0xff : 0x00;
}
else {
new[1] = new[0];
new[2] = new[0];
}
uint32_t new_color = *(uint32_t*)&new;
out[j * x + i] = new_color;
}
}
stbi_write_png(argv[2], x, y, 4, out, x * 4);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment