使用CImg和动态数组生成梯度

我正在尝试生成具有不同分辨率的png。但是,如果我使用动态数组,它只会生成灰色区域。这是我的代码(C++ 16 bit grayscale gradient image from 2D array)的源代码

void generate_horizontal_gradient(char fileName[],int width,int height,int offset,bool direction)
{
    unsigned short** buffer = new unsigned short* [height];
    for (int i = 0; i < height; i++)
    {
    buffer[i] = new unsigned short[width];
    }

    for (int i = 0; i < height; i++)
    {
        unsigned short temp_data = 65535;
        if (direction == true) {
            for (int j = width; j > 0; j--)
            {
                buffer[i][j] = temp_data;
                if (j < width - offset)
                {
                    temp_data -= 65535 / (width - offset);
                }
            }
        }
        else
        {
            for (int j = 0; j < width; j++)
            {
                buffer[i][j] = temp_data;
                if (j > offset)
                {
                    temp_data -= 65535 / (width - offset);
                }
            }
        }
    }
    auto hold_arr = (unsigned short*) &buffer[0][0];
    cimg_library::CImg<unsigned short> img(hold_arr,width,height);
    img.save_png(fileName);
}
wzq185833229 回答:使用CImg和动态数组生成梯度

显然,我对二维数组还不了解。通过一维数组解决了该问题:

void generate_horizontal_gradient(char fileName[],int width,int height,int offset,bool direction)
{   
unsigned short* buffer = new unsigned short[height * width];

//Add values to array.
for (int i = 0; i < height; i++)
{
    unsigned short temp_data = 65535;
    if (direction == true) {
        for (int j = width; j > 0; j--)
        {
            buffer[i* width +j] = temp_data;
            if (j < width - offset) temp_data -= 65535 / (width - offset);          
        }
    }
    else
    {
        for (int j = 0; j < width; j++)
        {
            buffer[i * width + j] = temp_data;
            if (j > offset) temp_data -= 65535 / (width - offset);
        }
    }
}

unsigned short* hold_arr = (unsigned short*)& buffer[0*0];
cimg_library::CImg<unsigned short> img(buffer,width,height);
img.save_png(fileName);
}
本文链接:https://www.f2er.com/3154476.html

大家都在问