我不明白为什么当我导出到 jpeg 时,每 1080 像素就会出现一条垂直线。我做错了什么?
完整仓库 -> https://github.com/ElPettego/swg_bg
垂直线示例 -> https://github.com/ElPettego/swg_bg/blob/master/swg_test.jpg
void export_jpg(std::vector<std::vector<int>> grid) {
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr);
FILE* outfile = fopen("swg_test.jpg", "wb");
if (!outfile) {
exit(1);
}
jpeg_create_compress(&cinfo);
jpeg_stdio_dest(&cinfo, outfile);
cinfo.image_width = width;
cinfo.image_height = height;
cinfo.input_components = 3;
cinfo.in_color_space = JCS_RGB;
jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, 100, TRUE);
jpeg_start_compress(&cinfo, TRUE);
while (cinfo.next_scanline < cinfo.image_height) {
JSAMPROW row_buffer = new JSAMPLE[cinfo.image_width * 3];
for (int x = 0; x < width; x++) {
row_buffer[x * 3] = 0;
row_buffer[x * 3 + 2] = 0;
row_buffer[x * 3 + 1] = grid[cinfo.next_scanline][x] ? 255 : 0;
}
jpeg_write_scanlines(&cinfo, &row_buffer, 1);
delete[] row_buffer;
}
jpeg_finish_compress(&cinfo);
fclose(outfile);
jpeg_destroy_compress(&cinfo);
}
我尝试修改new_ Generation函数中for循环的边界和导出质量,但错误仍然存在(https://github.com/ElPettego/swg_bg/blob/master/main.c%2B%2B)
简单的未定义行为。
但是,通过查看此处问题中的代码,您永远不会知道这一点,您需要查看未包含在存储库中的代码。
看看
grid
是如何创建的:
std::vector<std::vector<int>> grid(width, std::vector<int>(height, 1));
请注意,
width
定义了outer向量的大小,而height
定义了每个inner向量的大小。
现在看看您如何访问网格:
row_buffer[x * 3 + 1] = grid[cinfo.next_scanline][x] ? 255 : 0;
第一对括号取消引用外部向量,而第二对括号取消引用内部向量。这与向量的定义方式相反。由于宽度大于高度,因此您正在访问向量的越界元素。