dwgbmp.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. // dwgbmp.cpp
  2. // 单文件命令行工具:从 DWG 中提取内嵌预览图(BMP 或 PNG)
  3. //
  4. // 用法:
  5. // dwgbmp.exe <input.dwg> -> 默认输出 <input>.png
  6. // dwgbmp.exe <input.dwg> <output> -> 按扩展名: .png 转 PNG, 其他写 BMP
  7. //
  8. // VC2010 编译(命令行):
  9. // cl /EHsc dwgbmp.cpp
  10. // 若链接报错找不到 CImage 相关符号,在项目属性->链接器->附加依赖项 加 atls.lib
  11. //
  12. // 注意:本文件请保存为“带 BOM 的 UTF-8”或“GBK”,避免中文注释在 VC2010 下乱码。
  13. #include <cstdio>
  14. #include <cstdlib>
  15. #include <cstring>
  16. #include <string>
  17. #include <atlstr.h> // 必须在 atlimage.h 之前,提供 CString
  18. #include <atlimage.h> // CImage
  19. using std::string;
  20. // ----------------------------- 辅助函数 -----------------------------
  21. static bool ends_with_ci(const string& s, const string& suffix) {
  22. if (s.size() < suffix.size()) return false;
  23. for (size_t i = 0; i < suffix.size(); ++i) {
  24. char a = s[s.size() - suffix.size() + i];
  25. char b = suffix[i];
  26. if (a >= 'A' && a <= 'Z') a = a - 'A' + 'a';
  27. if (b >= 'A' && b <= 'Z') b = b - 'A' + 'a';
  28. if (a != b) return false;
  29. }
  30. return true;
  31. }
  32. enum OutFormat { OUT_BMP, OUT_PNG };
  33. static OutFormat detect_out_format(const char* path) {
  34. string p(path);
  35. if (ends_with_ci(p, ".png")) return OUT_PNG;
  36. return OUT_BMP;
  37. }
  38. static string make_default_output(const char* dwg_path) {
  39. string p(dwg_path);
  40. size_t dot = p.find_last_of('.');
  41. size_t sep = p.find_last_of("\\/");
  42. if (dot != string::npos && (sep == string::npos || dot > sep)) {
  43. p = p.substr(0, dot);
  44. }
  45. p += ".png";
  46. return p;
  47. }
  48. // 根据数据魔数判断实际图像格式
  49. enum DataKind { DATA_UNKNOWN, DATA_PNG, DATA_BMP_FILE, DATA_DIB };
  50. static DataKind detect_data_kind(const unsigned char* data, int size) {
  51. if (size >= 8 &&
  52. data[0] == 0x89 && data[1] == 0x50 && data[2] == 0x4E && data[3] == 0x47 &&
  53. data[4] == 0x0D && data[5] == 0x0A && data[6] == 0x1A && data[7] == 0x0A) {
  54. return DATA_PNG;
  55. }
  56. if (size >= 2 && data[0] == 'B' && data[1] == 'M') {
  57. return DATA_BMP_FILE;
  58. }
  59. if (size >= 40) {
  60. unsigned int biSize = 0;
  61. memcpy(&biSize, data, sizeof(unsigned int));
  62. if (biSize == 40 || biSize == 108 || biSize == 124) {
  63. return DATA_DIB;
  64. }
  65. }
  66. return DATA_UNKNOWN;
  67. }
  68. static int calc_palette_size(const unsigned char* dib, int dib_size) {
  69. if (dib_size < 40) return 0;
  70. unsigned int biSize = 0;
  71. memcpy(&biSize, dib, sizeof(unsigned int));
  72. if (biSize < 40 || (int)biSize > dib_size) return 0;
  73. unsigned short biBitCount = 0;
  74. memcpy(&biBitCount, dib + 14, sizeof(unsigned short));
  75. if (biBitCount > 8) return 0;
  76. return (1 << biBitCount) * 4;
  77. }
  78. static bool write_bmp_with_header(const char* bmp_path,
  79. const char* dib_data, int dib_size) {
  80. if (dib_size < 40) {
  81. fprintf(stderr, "[错误] DIB 数据太小 (%d 字节)\n", dib_size);
  82. return false;
  83. }
  84. const unsigned char* dib = (const unsigned char*)dib_data;
  85. unsigned int biSize = 0;
  86. memcpy(&biSize, dib, sizeof(unsigned int));
  87. int biWidth = 0, biHeight = 0;
  88. memcpy(&biWidth, dib + 4, sizeof(int));
  89. memcpy(&biHeight, dib + 8, sizeof(int));
  90. unsigned short biBitCount = 0;
  91. memcpy(&biBitCount, dib + 14, sizeof(unsigned short));
  92. unsigned int biCompression = 0;
  93. memcpy(&biCompression, dib + 16, sizeof(unsigned int));
  94. printf("[BMP] DIB 头: biSize=%u, %dx%d, 位深=%u, 压缩=%u\n",
  95. biSize, biWidth, biHeight,
  96. (unsigned)biBitCount, biCompression);
  97. if (biSize < 40 || (int)biSize > dib_size) {
  98. fprintf(stderr, "[错误] DIB 头大小异常: biSize=%u\n", biSize);
  99. return false;
  100. }
  101. int palette_size = calc_palette_size(dib, dib_size);
  102. int pixel_offset = 14 + (int)biSize + palette_size;
  103. printf("[BMP] 调色板大小=%d 字节, 像素数据偏移=%d\n",
  104. palette_size, pixel_offset);
  105. FILE* fp = fopen(bmp_path, "wb");
  106. if (!fp) {
  107. fprintf(stderr, "[错误] 无法创建 BMP 文件: %s\n", bmp_path);
  108. return false;
  109. }
  110. unsigned char file_header[14] = {0};
  111. file_header[0] = 'B';
  112. file_header[1] = 'M';
  113. int file_size = 14 + dib_size;
  114. memcpy(file_header + 2, &file_size, 4);
  115. memcpy(file_header + 10, &pixel_offset, 4);
  116. fwrite(file_header, 1, 14, fp);
  117. fwrite(dib_data, 1, dib_size, fp);
  118. fclose(fp);
  119. printf("[BMP] 写出完成: %d 字节\n", file_size);
  120. return true;
  121. }
  122. // ----------------------------- 核心解析 -----------------------------
  123. static int extract_preview(const char* dwg_path,
  124. const char* tmp_bmp_path,
  125. const char* out_png_path,
  126. bool* out_is_png) {
  127. *out_is_png = false;
  128. printf("[1/6] 打开 DWG: %s\n", dwg_path);
  129. FILE* fd = fopen(dwg_path, "rb");
  130. if (!fd) {
  131. fprintf(stderr, "[错误] 无法打开 DWG 文件: %s\n", dwg_path);
  132. return 1;
  133. }
  134. fseek(fd, 13, SEEK_SET);
  135. unsigned int sentinel_pos = 0;
  136. if (fread(&sentinel_pos, sizeof(unsigned int), 1, fd) != 1) {
  137. fprintf(stderr, "[错误] 读取预览指针失败\n");
  138. fclose(fd);
  139. return 2;
  140. }
  141. printf("[2/6] 预览容器指针 sentinel_pos = 0x%08X (%u)\n",
  142. sentinel_pos, sentinel_pos);
  143. const int SIZE_SN = 39;
  144. char buf[SIZE_SN] = {0};
  145. unsigned char SN[] = {0x1F, 0x25, 0x6D, 0x07, 0xD4, 0x36, 0x28, 0x28,
  146. 0x9D, 0x57, 0xCA, 0x3F, 0x9D, 0x44, 0x10, 0x2B};
  147. fseek(fd, sentinel_pos, SEEK_SET);
  148. if (fread(buf, SIZE_SN, 1, fd) != 1) {
  149. fprintf(stderr, "[错误] 读取预览容器头失败\n");
  150. fclose(fd);
  151. return 3;
  152. }
  153. bool isdwg = true;
  154. for (int i = 0; i != 16; i++) {
  155. isdwg = isdwg && ((unsigned char)buf[i] == SN[i]);
  156. }
  157. unsigned char image_type = (unsigned char)buf[20];
  158. printf("[3/6] 哨兵校验: %s, 预览类型码 = %u (%s)\n",
  159. isdwg ? "OK" : "BAD", (unsigned)image_type,
  160. image_type == 2 ? "BMP" :
  161. (image_type == 6 ? "PNG" : "未知"));
  162. if (!isdwg || (image_type != 2 && image_type != 6)) {
  163. fprintf(stderr,
  164. "[错误] 不是有效的 DWG 预览容器,或类型不支持 "
  165. "(哨兵=%s, 类型=%u)\n",
  166. isdwg ? "OK" : "BAD", (unsigned)image_type);
  167. fclose(fd);
  168. return 4;
  169. }
  170. int data_size = 0;
  171. memcpy(&data_size, &buf[35], sizeof(int));
  172. int pos = 0;
  173. memcpy(&pos, &buf[31], sizeof(int));
  174. printf("[4/6] 预览数据: pos = %d, data_size = %d 字节\n", pos, data_size);
  175. if (data_size <= 0 || pos <= 0) {
  176. fprintf(stderr, "[错误] 非法的预览数据大小/偏移: size=%d pos=%d\n",
  177. data_size, pos);
  178. fclose(fd);
  179. return 5;
  180. }
  181. char* raw_buf = new char[data_size];
  182. fseek(fd, pos, SEEK_SET);
  183. if ((int)fread(raw_buf, 1, data_size, fd) != data_size) {
  184. fprintf(stderr, "[错误] 读取预览数据失败\n");
  185. delete[] raw_buf;
  186. fclose(fd);
  187. return 6;
  188. }
  189. fclose(fd);
  190. printf("[5/6] 读取预览数据成功 (%d 字节)\n", data_size);
  191. // ---- 关键:用数据魔数判定真实格式,不再盲信类型码 ----
  192. DataKind kind = detect_data_kind((const unsigned char*)raw_buf, data_size);
  193. printf("[5.5/6] 数据魔数判定: %s\n",
  194. kind == DATA_PNG ? "PNG" :
  195. kind == DATA_BMP_FILE ? "完整 BMP 文件(带 BM 头)" :
  196. kind == DATA_DIB ? "裸 DIB(需补 BMP 头)" :
  197. "未知");
  198. bool ok = false;
  199. if (kind == DATA_PNG) {
  200. printf("[6/6] 实际为 PNG,原样写出到: %s\n", out_png_path);
  201. FILE* fp = fopen(out_png_path, "wb");
  202. if (fp) {
  203. ok = (fwrite(raw_buf, 1, data_size, fp) == (size_t)data_size);
  204. fclose(fp);
  205. }
  206. *out_is_png = true;
  207. } else if (kind == DATA_BMP_FILE) {
  208. printf("[6/6] 数据已带 BMP 文件头,直接写出到临时文件: %s\n",
  209. tmp_bmp_path);
  210. FILE* fp = fopen(tmp_bmp_path, "wb");
  211. if (fp) {
  212. ok = (fwrite(raw_buf, 1, data_size, fp) == (size_t)data_size);
  213. fclose(fp);
  214. }
  215. *out_is_png = false;
  216. } else if (kind == DATA_DIB) {
  217. printf("[6/6] 裸 DIB,动态补 BMP 文件头写到: %s\n", tmp_bmp_path);
  218. ok = write_bmp_with_header(tmp_bmp_path, raw_buf, data_size);
  219. *out_is_png = false;
  220. } else {
  221. fprintf(stderr,
  222. "[错误] 无法识别预览数据格式。前 16 字节: ");
  223. for (int i = 0; i < 16 && i < data_size; ++i) {
  224. fprintf(stderr, "%02X ", (unsigned char)raw_buf[i]);
  225. }
  226. fprintf(stderr, "\n");
  227. ok = false;
  228. }
  229. delete[] raw_buf;
  230. return ok ? 0 : 7;
  231. }
  232. // ----------------------------- 主流程 -----------------------------
  233. static bool DWGThumbnail(const char* dwg_filename, const char* out_filename) {
  234. printf("==== DWG 预览图提取 ====\n");
  235. printf("输入: %s\n", dwg_filename);
  236. printf("输出: %s\n", out_filename);
  237. string ext(dwg_filename);
  238. if (!ends_with_ci(ext, ".dwg")) {
  239. fprintf(stderr, "[错误] 输入文件不是 .dwg: %s\n", dwg_filename);
  240. return false;
  241. }
  242. OutFormat out_fmt = detect_out_format(out_filename);
  243. printf("目标格式: %s\n", out_fmt == OUT_PNG ? "PNG" : "BMP");
  244. char tmp_bmp[L_tmpnam + 8] = {0};
  245. if (!tmpnam(tmp_bmp)) {
  246. fprintf(stderr, "[错误] 无法生成临时文件名\n");
  247. return false;
  248. }
  249. strcat(tmp_bmp, ".bmp");
  250. bool is_png = false;
  251. int rc = extract_preview(dwg_filename, tmp_bmp, out_filename, &is_png);
  252. if (rc != 0) {
  253. remove(tmp_bmp);
  254. fprintf(stderr, "[失败] 提取预览图失败,错误码 %d\n", rc);
  255. return false;
  256. }
  257. bool ok = true;
  258. if (is_png) {
  259. if (out_fmt == OUT_BMP) {
  260. fprintf(stderr, "[警告] 实际预览为 PNG,目标扩展名为 .bmp,"
  261. "文件内容仍是 PNG\n");
  262. }
  263. ok = true;
  264. printf("[完成] PNG 预览已直接写出\n");
  265. } else {
  266. if (out_fmt == OUT_PNG) {
  267. printf("[转换] BMP -> PNG,使用 CImage...\n");
  268. CImage image;
  269. HRESULT hr = image.Load(tmp_bmp);
  270. if (FAILED(hr)) {
  271. fprintf(stderr, "[错误] CImage 加载 BMP 失败, hr=0x%08X\n",
  272. (unsigned)hr);
  273. ok = false;
  274. } else {
  275. hr = image.Save(out_filename);
  276. if (FAILED(hr)) {
  277. fprintf(stderr, "[错误] CImage 保存 PNG 失败, hr=0x%08X\n",
  278. (unsigned)hr);
  279. ok = false;
  280. } else {
  281. printf("[完成] BMP 已转换为 PNG\n");
  282. }
  283. }
  284. } else {
  285. printf("[写出] 目标为 BMP,移动临时文件到目标路径...\n");
  286. if (rename(tmp_bmp, out_filename) != 0) {
  287. FILE* in = fopen(tmp_bmp, "rb");
  288. FILE* out = fopen(out_filename, "wb");
  289. if (!in || !out) {
  290. if (in) fclose(in);
  291. if (out) fclose(out);
  292. ok = false;
  293. } else {
  294. char cbuf[4096];
  295. size_t n;
  296. while ((n = fread(cbuf, 1, sizeof(cbuf), in)) > 0) {
  297. fwrite(cbuf, 1, n, out);
  298. }
  299. fclose(in);
  300. fclose(out);
  301. ok = true;
  302. }
  303. }
  304. if (ok) printf("[完成] BMP 已写出\n");
  305. }
  306. }
  307. remove(tmp_bmp);
  308. return ok;
  309. }
  310. int main(int argc, char* argv[]) {
  311. if (argc != 2 && argc != 3) {
  312. fprintf(stderr,
  313. "用法:\n"
  314. " %s <input.dwg> 默认输出 <input>.png\n"
  315. " %s <input.dwg> <output> 按扩展名: .png 转 PNG, 其他写 BMP\n"
  316. " 从 DWG 文件中提取内嵌预览图(BMP 或 PNG)。\n",
  317. argv[0], argv[0]);
  318. return 1;
  319. }
  320. string out_path;
  321. if (argc == 3) {
  322. out_path = argv[2];
  323. } else {
  324. out_path = make_default_output(argv[1]);
  325. }
  326. bool ok = DWGThumbnail(argv[1], out_path.c_str());
  327. if (ok) {
  328. printf("\n[成功] 已输出: %s\n", out_path.c_str());
  329. return 0;
  330. }
  331. fprintf(stderr, "\n[失败] 未能提取预览图\n");
  332. return 2;
  333. }