问题
I am trying to write a simple image file to disk using stb_image_write. I use the simplest test case : a 128 by 128 pixels RGB image.
I found this example online, and the guy seems to say that it works fine, plus it looks exactly like what I have been writing for 2 hours :
void save_image(int w, int h, int channels_num)
{
int data[w * h * channels_num];
int index = 0;
for (int j = h - 1; j >= 0; --j)
{
for (int i = 0; i < w; ++i)
{
float r = (float)i / (float)w;
float g = (float)j / (float)h;
float b = 0.2f;
int ir = int(255.0 * r);
int ig = int(255.0 * g);
int ib = int(255.0 * b);
data[index++] = ir;
data[index++] = ig;
data[index++] = ib;
}
}
stbi_write_jpg("jpg_test_.jpg", w, h, channels_num, data, 100);
}
save_image(128, 128, 3);
The result should be a nice color gradient, but all I can get is a valid file with some vertical red, green, blue and black lines. Dimensions of the image are ok though. I really don't find the solution here. I am on linux Jessie. Could there be 'endianess' issue or something like that?
回答1:
The question was answered in the comments. I had to replace : int data[] by : unsigned char data[];
回答2:
=============== This part was not accurate. please see my solution part below ====
int data[w * h * channels_num]; is ok, that's not the reason you failed.
Change this line
stbi_write_jpg("jpg_test_.jpg", w, h, channels_num, data, 100);
to
stbi_write_jpg("jpg_test_.jpg", w, h, channels_num, data, w * sizeof(int));
You will get what you want. The last parameters, I believe it is stride. If so, stride means the offset between two lines. Based on your question, I assume you have 128 X 128 X 32bit color. Then stride will be w * sizeof(int).
If NOT, let me know.
Sorry I was in a hurry to rush to a meeting.
============ This part is the solution part ====
Yes,
int data[w * h * channels_num];
should be
unsigned char data[w * h * channels_num];
Plus,
stbi_write_jpg("jpg_test_.jpg", w, h, channels_num, data, 100);
should be changed to
stbi_write_jpg("jpg_test_.jpg", w, h, channels_num, data, w * channels_num);
Full solution
void save_image(int w, int h, int channels_num)
{
unsigned char data[w * h * channels_num];
int index = 0;
for (int j = h - 1; j >= 0; --j)
{
for (int i = 0; i < w; ++i)
{
data[index++] = (unsigned char)(255.0 * i / w);
data[index++] = (unsigned char)(255.0 * j / h);
data[index++] = (unsigned char)(255.0 * 0.2);
}
}
stbi_write_jpg("jpg_test_.jpg", w, h, channels_num, data, w * channels_num);
}
来源:https://stackoverflow.com/questions/56039401/stb-image-write-issue