cmathppm

Vertical gradient formula


I want to write a C program that produces 1000x1000 .ppm file, showing a vertical gradient from black(left) to white (right). Now, if the picture would be 256x256 it would be easy:

P3
256 256
255
0 0 0 1 1 1 2 2 2 .... 255 255 255
0 0 0 1 1 1 2 2 2 .... 255 255 255
.
.
.
0 0 0 1 1 1 2 2 2 .... 255 255 255

Thing is, since it must be 1000x1000 (exceeding 255), I'm not sure what formula I should follow to get a perfect gradient. Any ideas?


Solution

  • You can scale the pixel's color index by the total desired width to generate a decimal between 0 and 1 that represents its normalized position within the line. Then multiply by 256 to scale it to the color range. This gives:

    int color = (float)offset / width * 256;
    

    Runnable proof of concept:

    const makeGradient = (gradEl, width=500, height=500) => {
      let html = "";
      
      for (let offset = 0; offset < width; offset++) {
        const color = offset / width * 256; // JS does float division
        html += `
          <div style="
            background-color: rgb(${color}, ${color}, ${color});
            width: 1px; height: ${height}px;
          "></div>
        `;
      }
      
      gradEl.innerHTML = html;
    };
    
    const gradEl = document.querySelector("#gradient");
    makeGradient(gradEl);
    document.querySelector("input")
      .addEventListener("keyup", e => {
        makeGradient(gradEl, +e.target.value || null);
      });
    body {
      background: blue;
    }
    
    #gradient {
      display: flex;
    }
    <input value="500" type="number" min="0" max="2000">
    <div id="gradient"></div>