用C语言基本函数写一个打开jpg图像并且显示其像素点矩阵的代码
时间: 2023-05-20 21:03:18 浏览: 141
以下是用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 *fp = fopen(filename, "rb");
if (!fp) {
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, fp);
jpeg_read_header(&cinfo, TRUE);
jpeg_start_decompress(&cinfo);
int width = cinfo.output_width;
int height = cinfo.output_height;
int num_components = cinfo.output_components;
int row_stride = width * num_components;
unsigned char *buffer = (unsigned char *) malloc(row_stride * height);
unsigned char *row_pointer = buffer;
while (cinfo.output_scanline < height) {
jpeg_read_scanlines(&cinfo, &row_pointer, 1);
row_pointer += row_stride;
}
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
fclose(fp);
printf("Image size: %d x %d\n", width, height);
printf("Pixel matrix:\n");
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
for (int k = 0; k < num_components; k++) {
printf("%d ", buffer[i * row_stride + j * num_components + k]);
}
printf("\n");
}
}
free(buffer);
return 0;
}
```
这个程序使用了 libjpeg 库来读取 JPG 图像文件,首先打开文件,然后使用 `jpeg_create_decompress` 创建一个解压缩对象,使用 `jpeg_stdio_src` 将文件指针传递给解压缩对象,使用 `jpeg_read_header` 读取 JPG 文件头信息,使用 `jpeg_start_decompress` 开始解压缩,使用 `jpeg_read_scanlines` 读取每一行像素点数据,最后使用 `jpeg_finish_decompress` 结束解压缩,释放资源。在读取像素点数据时,将每个像素点的 RGB 值打印出来。
阅读全文