C語言是一種廣泛應用的編程語言,可以用于開發各種應用程序,包括圖像處理軟件。JSON(JavaScript對象表示法)則是一種輕量級的數據格式,具有廣泛的應用領域。本文將介紹如何使用C語言處理圖像數據并將其轉換為JSON格式。
#include#include #include #include #include #include #include // 讀取JPEG圖像文件并將數據轉換為JSON格式 int main(int argc, char **argv) { // 讀取JPEG圖像文件數據 FILE *infile; struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; unsigned char *image_data; int line_width, row_stride, image_size; infile = fopen("test.jpg", "rb"); if (infile == NULL) { fprintf(stderr, "Can't open jpeg file\n"); exit(1); } cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); jpeg_stdio_src(&cinfo, infile); jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); line_width = cinfo.output_width * cinfo.output_components; row_stride = line_width; image_size = cinfo.output_height * row_stride; image_data = malloc(image_size); JSAMPARRAY buffer = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, line_width, 1); unsigned char *p_image_data = image_data; while (cinfo.output_scanline< cinfo.output_height) { jpeg_read_scanlines(&cinfo, buffer, 1); memcpy(p_image_data, buffer[0], row_stride); p_image_data += row_stride; } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); fclose(infile); // 將圖像數據轉換為JSON格式 cJSON *root = cJSON_CreateObject(); cJSON_AddNumberToObject(root, "width", cinfo.output_width); cJSON_AddNumberToObject(root, "height", cinfo.output_height); cJSON_AddNumberToObject(root, "channels", cinfo.output_components); cJSON_AddNumberToObject(root, "size", image_size); cJSON *data_array = cJSON_CreateArray(); for (int i = 0; i< image_size; ++i) { cJSON_AddItemToArray(data_array, cJSON_CreateNumber(image_data[i])); } cJSON_AddItemToObject(root, "data", data_array); char *json_str = cJSON_Print(root); printf("%s\n", json_str); // 釋放內存 free(image_data); free(json_str); cJSON_Delete(root); return 0; }
上述代碼使用了libjpeg庫讀取JPEG圖像文件的數據,然后使用cJSON庫將圖像數據轉換為JSON格式,最終打印出JSON字符串。通過這種方式可以輕松地將圖像數據存儲到數據庫或發送到網絡,方便圖像數據的傳輸和處理。