T
T
tj572018-11-25 23:26:21
C++ / C#
tj57, 2018-11-25 23:26:21

How to implement a gray color gradient without using graphics libraries (OpenCV, etc.) in C/C++?

How, using standard tools, to write an array to a text file that will display a gray gradient, as in the picture? 5bfb01aa7d25a769606500.jpeg. The gradient, of course, will not turn out smooth, as in the picture, but it should look something like this.
The bottom line is that white color corresponds to the value 255, black - 0. The size of the picture is set by the user. The text file is a .pgm image that can be converted to .png using a converter. As an example, I can give a program that draws a black line on a white background using random coordinates:
https://gist.github.com/tjarrow/21ad2bf49f801f44db...
Line example:
5bfb056a3ec59983049117.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sddvxd, 2018-11-26
@tj57

If you really want an idea and not a finished program code, here's my idea:

int rows = 0, cols = 0;
    cout << "Enter size (Example: 200x200)\n";
    cin >> rows >> cols;
    if(rows <= 0 || cols <= 0) throw runtime_error("Bad size");
    int pixmap[rows][cols];
    for(int i = 0; i < rows; ++i){
        double position = double(i) / rows;   //Вычисляем "высоту"
        int color = position * 255;                 //и находим подходящий цвет
        cout << position << " " << color << '\n';
        for(int j = 0; j < cols; ++j)
            pixmap[i][j] = color;
    }

FINAL VERSION:
#include <iostream>
#include <cstdio>
using namespace std;

void main()
{
    int rows = 0, cols = 0;
    char* filename = "test.pgm";
    cout << "Enter size and filename (Example: 200x200 mygradient.pgm)\n";
    cin >> rows >> cols >> filename;
    if(rows <= 0 || cols <= 0) throw runtime_error("Bad size");
    FILE* pfile = fopen(filename, "w");
    fprintf(pfile, "P2\n%d %d\n255\n", cols, rows);
    for(int i = 0; i < rows; ++i){
        double position = double(i) / rows;
        int color = position * 255;
        cout << position << " " << color << "\n";
        for(int j = 0; j < cols; ++j)
            fprintf(pfile, "%d ", color);
        fprintf(pfile, "\n");
    }
}

Enter for example like this: 1500x400 file.pgm
5bfb1d672efdc256620573.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question