// write png image with stb_image_write.h #include #define STB_IMAGE_STATIC #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #define STB_IMAGE_WRITE_STATIC #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage\n\t02_writeimage.exe IN.png"); } auto filename = argv[1]; unsigned char *pixels; int width; int height; int bpp; // load image pixels = stbi_load(filename, &width, &height, &bpp, 0); printf("Image size %d x %d\n", width, height); printf("Image bpp %d\n", bpp); for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) { int idx = (y * width + x) * bpp; unsigned int r = (unsigned int)pixels[idx + 0]; unsigned int g = (unsigned int)pixels[idx + 1]; unsigned int b = (unsigned int)pixels[idx + 2]; // convert greyscale if (1) { double grey = 0.299 * (double)r + 0.587 * (double)g + 0.114 * (double)b; if (grey < 0) grey = 0; if (grey > 255) grey = 255; unsigned int ui_grey = (unsigned int)grey; pixels[idx + 0] = ui_grey; pixels[idx + 1] = ui_grey; pixels[idx + 2] = ui_grey; } } // write image if (stbi_write_png("out.png", width, height, 3, pixels, width * 3)) { printf("Save out.png\n"); } else { printf("Failure save.\n"); } stbi_image_free(pixels); }