用C语言写一个打开jpg图像并且显示其像素点矩阵的代码
时间: 2023-05-20 21:03:17 浏览: 306
C语言读取图片(C代码)
4星 · 用户满意度95%
以下是用C语言打开jpg图像并显示其像素点矩阵的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <jpeglib.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <filename>\n", argv[0]);
return 1;
}
char *filename = argv[1];
FILE *file = fopen(filename, "rb");
if (!file) {
printf("Failed to open file: %s\n", filename);
return 1;
}
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, file);
jpeg_read_header(&cinfo, TRUE);
jpeg_start_decompress(&cinfo);
int row_stride = cinfo.output_width * cinfo.output_components;
unsigned char *buffer = (unsigned char*)malloc(row_stride);
while (cinfo.output_scanline < cinfo.output_height) {
jpeg_read_scanlines(&cinfo, &buffer, 1);
for (int i = 0; i < row_stride; i++) {
printf("%d ", buffer[i]);
}
printf("\n");
}
free(buffer);
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
fclose(file);
return 0;
}
```
这段代码使用了libjpeg库来解码jpg图像,首先打开文件,然后创建一个jpeg解码器,读取图像头部信息,开始解码,逐行读取像素点数据并输出到控制台,最后释放内存并关闭文件。
阅读全文