我正在使用libjpeg解压缩JPEG图像并将其写入BMP文件。假设将图像宽度设置为2550像素(每像素24位(3字节)),则所得的行宽度将不是4的倍数。如何在4字节边界处对齐每一行?

struct jpeg_decompress_struct cinfo;
unsigned int bytesPerRow = cinfo.output_width * cinfo.num_components;
unsigned int colColor;
FILE *bmpFile = NULL;

while (cinfo.output_scanline < cinfo.image_height) {

    JSAMPROW row_pointer[1];
    row_pointer[0] = raw_image
            + cinfo.output_scanline * bytesPerRow;
    jpeg_read_scanlines(&cinfo, row_pointer, 1);
    for (colColor = 0; colColor < cinfo.image_width; colColor++) {

        /* BMP scanlines should be aligned at 4-byte boundary */

    }

    /* write each row to bmp file */
    fwrite(row_pointer[0], 1, bytesPerRow, bmpFile);
}

最佳答案

bytesPerRow = 4 *((cinfo.output_width * cinfo.num_components + 3)/
  4); –汉斯·帕桑(Hans Passant)


就四舍五入而言,该公式是正确的,但使用乘数cinfo.num_components则不正确;根据USING THE IJG JPEG LIBRARY


  每条扫描线将需要output_width * output_components个JSAMPLE
  在您的输出缓冲区中...
  
  输出数组必须为output_width * output_components
  JSAMPLE宽。


所以是

unsigned int bytesPerRow = (cinfo.output_width * cinfo.output_components + 3) / 4 * 4;

10-06 13:39