Skip to content

Instantly share code, notes, and snippets.

@Leandros
Created March 8, 2018 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Leandros/235f4d72e076b17a3e28a88c8ecca200 to your computer and use it in GitHub Desktop.
Save Leandros/235f4d72e076b17a3e28a88c8ecca200 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <math.h>
#define clamp(d, min, max) ((d) < (min) ? (min) : ((d) > (max) ? (max) : (d)))
float
sRGB_encode(float v)
{
if (v <= 0.0031308f)
return 12.92f * v;
return 1.055f * powf(v, 1.0f / 2.4f) - 0.055f;
}
int
encode(float v)
{
return (unsigned char)roundf(sRGB_encode(clamp(v, 0.0f, 1.0f)) * 255.0f);
}
static FILE *
open_ppm(char const *name, int width, int height)
{
FILE *fp = fopen(name, "wb");
fprintf(fp, "P3\n");
fprintf(fp, "%d %d\n", width, height);
fprintf(fp, "255\n");
return fp;
}
static void
write_pixel_u8(FILE *fp, int r, int g, int b)
{
fprintf(fp, "%d %d %d\n", r, g, b);
}
int
main()
{
FILE *fp = open_ppm("image.ppm", 255, 200);
{
int x, y, r, g, b;
for (y = 0; y < 100; ++y) {
r = 0, g = 0, b = 0;
for (x = 0; x < 255; ++x) {
write_pixel_u8(fp, r++, g++, b++);
}
}
}
{
int x, y, r, g, b;
for (y = 100; y < 200; ++y) {
r = 0, g = 0, b = 0;
for (x = 0; x < 255; ++x) {
write_pixel_u8(fp,
encode(r++ / 255.0f),
encode(g++ / 255.0f),
encode(b++ / 255.0f));
}
}
fclose(fp);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment