watermark.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. import fs from "fs";
  2. import path from "path";
  3. // import sizeOf from "image-size";
  4. import mkdirp from "mkdirp";
  5. import { Store, Student } from "@/types";
  6. import gmType from "gm";
  7. const arrayBufferToBase64Img = (buffer: ArrayBuffer) => {
  8. const str = String.fromCharCode(...new Uint8Array(buffer));
  9. return `data:image/jpg;base64,${window.btoa(str)}`;
  10. };
  11. let gm = null as unknown as typeof gmType;
  12. export async function addWatermark(
  13. store: Store,
  14. imageData: ArrayBuffer,
  15. imageWidth: number,
  16. imageHeight: number,
  17. filePath: string[],
  18. student: Student,
  19. index: number,
  20. trackMode: string,
  21. x = 0.01,
  22. y = 0.03,
  23. colorMap: any = {},
  24. headerColorMap: any = {},
  25. onlyUsePdf = false
  26. ): Promise<boolean | string> {
  27. const canShowDouble = store.env.user.doubleTrack;
  28. // console.log("双评是否展示的配置为:", canShowDouble);
  29. const file = path.join(...filePath);
  30. if (
  31. index !== 1 &&
  32. (student.tags == undefined || student.tags[index] == undefined)
  33. ) {
  34. return await saveImage(store, imageData, filePath, onlyUsePdf);
  35. }
  36. if (store.pageInputs["/image-download"].append && fs.existsSync(file)) {
  37. console.log(file + " already exists");
  38. return true;
  39. }
  40. x = imageWidth * x;
  41. y = imageHeight * y;
  42. if (!gm) {
  43. gm =
  44. store.config.imagemagickDev != undefined
  45. ? require("gm").subClass({
  46. imageMagick: true,
  47. appPath: store.config.imagemagickDev,
  48. })
  49. : require("gm").subClass({
  50. imageMagick: true,
  51. appPath: path.join(__dirname, "../../imagemagick/"), // windows打包进程序了
  52. });
  53. // console.log(path.join(__dirname, "../../imagemagick/"));
  54. // console.log(path.join(__dirname, store.config.imagemagickDev));
  55. require("gm-base64");
  56. }
  57. const fontFile = store.config.watermark.fontFile;
  58. const color = store.config.watermark.color;
  59. const image = Buffer.from(imageData);
  60. // const size = sizeOf(image);
  61. // console.log(size);
  62. const imgData = gm(image);
  63. const drawText = (l: number, t: number, content: string) => {
  64. const len = (content || "").length;
  65. const top = t < 25 ? 50 : t + 25 > imageHeight ? imageHeight : t + 25;
  66. const left = l > imageWidth - 25 ? imageWidth - 25 * len : l;
  67. imgData.drawText(left, top, content);
  68. };
  69. //添加第一页的得分明细
  70. if (index == 1) {
  71. //初始坐标
  72. // let x = 30;
  73. // let y = 10;
  74. //最大宽/高限制
  75. const fontSize = store.config.watermark.fontSize || 30;
  76. // const maxX = imageWidth / 2 - x * 2;
  77. const saveX = x;
  78. let dynamicX = x;
  79. const maxStartX = imageWidth - fontSize * 0.7 * 5;
  80. const nextLineStartX = x + fontSize * 0.7 * 4;
  81. const height = fontSize + 10;
  82. //计算总分
  83. const totalScore =
  84. (parseFloat(student.objectiveScore) || 0) +
  85. (parseFloat(student.subjectiveScore) || 0);
  86. //显示总分明细
  87. imgData.font(fontFile, fontSize).fill(color);
  88. drawText(x, (y += height), "成绩明细");
  89. //普通考试模式,按客观+主观模式显示总分
  90. if (trackMode === "1") {
  91. drawText(
  92. x,
  93. (y += height),
  94. "总分=(客观+主观) | " +
  95. totalScore +
  96. "=" +
  97. student.objectiveScore +
  98. "+" +
  99. student.subjectiveScore
  100. );
  101. }
  102. //研究生考试模式,只显示总分
  103. else if (trackMode === "2") {
  104. drawText(x, (y += height), "总分=" + totalScore + "分");
  105. }
  106. //显示客观题明细
  107. if (
  108. student.objectiveScoreDetail &&
  109. student.objectiveScoreDetail.length > 0
  110. ) {
  111. const title = "大题号 | 大题总分";
  112. drawText(x, (y += height), title);
  113. const map: any = {};
  114. for (let i = 0; i < student.objectiveScoreDetail.length; i++) {
  115. const item = student.objectiveScoreDetail[i];
  116. if (!map[item.mainNumber]) {
  117. map[item.mainNumber] = [item];
  118. } else {
  119. map[item.mainNumber].push(item);
  120. }
  121. }
  122. for (const mainNumber in map) {
  123. const arr = map[mainNumber];
  124. const mainTotalScore =
  125. arr.reduce((num: number, item: any) => {
  126. return num + item.score * 100;
  127. }, 0) / 100;
  128. drawText(x, (y += height), `${mainNumber} | ${mainTotalScore}`);
  129. if (store.pageInputs["/image-download"].showSubScore) {
  130. dynamicX = saveX;
  131. drawText((dynamicX += fontSize * 0.7 * 5), y, ":");
  132. for (let i = 0; i < arr.length; i++) {
  133. const v = arr[i];
  134. const joinStr = i == arr.length - 1 ? "" : ",";
  135. if (dynamicX > maxStartX) {
  136. dynamicX = nextLineStartX;
  137. y += height;
  138. }
  139. drawText(
  140. (dynamicX += (v.score + " ").length * fontSize * 0.7),
  141. y,
  142. v.score + joinStr
  143. );
  144. }
  145. }
  146. }
  147. }
  148. // if (
  149. // student.objectiveScoreDetail &&
  150. // student.objectiveScoreDetail.length > 0
  151. // ) {
  152. // const lines = [];
  153. // let array = [];
  154. // //前置提示文字的字符数
  155. // let count = 10;
  156. // lines.push(array);
  157. // for (let i = 0; i < student.objectiveScoreDetail.length; i++) {
  158. // const detail = student.objectiveScoreDetail[i];
  159. // const content =
  160. // detail.answer + ":" + (detail.score === -1 ? "未选做" : detail.score);
  161. // //超长后另起一行显示客观题
  162. // if ((count + content.length) * fontSize * 0.7 > maxX) {
  163. // array = [];
  164. // lines.push(array);
  165. // count = 10;
  166. // }
  167. // array.push(content);
  168. // count += content.length;
  169. // }
  170. // //显示所有行的客观题明细
  171. // for (let l = 0; l < lines.length; l++) {
  172. // // FIXME: 要在小个版本修复
  173. // // 事先判断,能否打印,情况较多,比如客观题多个答案
  174. // // 事后报错,不让错误的数据保存
  175. // // if (y + height + 15 > imageHeight) {
  176. // // y = startY;
  177. // // x += width;
  178. // // }
  179. // drawText(x, (y += height), "客观题识别结果 | " + lines[l].join(";"));
  180. // }
  181. // }
  182. //显示复核人
  183. // if (student.inspector) {
  184. // drawText(x, (y += height), "复核人: " + student.inspector.loginName);
  185. // }
  186. if (student.inspector && student.inspector.length) {
  187. const allNameStr = student.inspector
  188. .map((item: any) => item.loginName)
  189. .join("、");
  190. drawText(x, (y += height), "复核人: " + allNameStr);
  191. }
  192. //显示主观题明细
  193. if (
  194. student.subjectiveScoreDetail &&
  195. student.subjectiveScoreDetail.length > 0
  196. ) {
  197. //普通考试模式,按小题显示明细
  198. if (trackMode === "1") {
  199. const title = "主观题号 | 分数 | 评卷员 | 仲裁员";
  200. const startY = y;
  201. let width = title.length * fontSize;
  202. drawText(x, (y += height), title);
  203. for (let i = 0; i < student.subjectiveScoreDetail.length; i++) {
  204. const detail = student.subjectiveScoreDetail[i];
  205. //超过最大高度了则另起一列
  206. if (y + height + 15 > imageHeight) {
  207. y = startY;
  208. x += width;
  209. drawText(x, (y += height), title);
  210. }
  211. const content =
  212. detail.mainNumber +
  213. "-" +
  214. detail.subNumber +
  215. " : " +
  216. (detail.score === -1 ? "未选做" : detail.score) +
  217. " " +
  218. (detail.marker || "") +
  219. " " +
  220. (detail.header || "");
  221. width = Math.max(width, content.length * fontSize);
  222. drawText(x, (y += height), content);
  223. }
  224. }
  225. //研究生考试模式,按分组显示明细
  226. else if (trackMode === "2") {
  227. const title = "评卷分组 | 总分 | 评卷员";
  228. const startY = y;
  229. let width = title.length * fontSize;
  230. drawText(x, (y += height), title);
  231. //所有小题得分按评卷分组聚合
  232. let maxGroupNumber = 0;
  233. const groups = {};
  234. for (let i = 0; i < student.subjectiveScoreDetail.length; i++) {
  235. const detail = student.subjectiveScoreDetail[i];
  236. let group = groups[detail.groupNumber];
  237. if (group == undefined) {
  238. group = {
  239. number: detail.groupNumber,
  240. score: 0,
  241. title: {},
  242. titleString: [],
  243. marker: {},
  244. markerString: [],
  245. header: {},
  246. headerString: [],
  247. subScores: [],
  248. };
  249. groups[detail.groupNumber] = group;
  250. maxGroupNumber = Math.max(maxGroupNumber, group.number);
  251. }
  252. group.subScores.push(detail.score === -1 ? 0 : detail.score);
  253. group.score =
  254. (group.score * 1000 +
  255. (detail.score === -1 ? 0 : detail.score) * 1000) /
  256. 1000;
  257. if (detail.mainTitle && !group.title[detail.mainTitle]) {
  258. group.titleString.push(detail.mainTitle);
  259. group.title[detail.mainTitle] = true;
  260. }
  261. if (detail.marker && !group.marker[detail.marker]) {
  262. group.markerString.push(detail.marker);
  263. group.marker[detail.marker] = true;
  264. }
  265. if (detail.header && !group.header[detail.header]) {
  266. group.headerString.push(detail.header);
  267. group.header[detail.header] = true;
  268. }
  269. }
  270. for (let i = 1; i <= maxGroupNumber; i++) {
  271. const group = groups[i];
  272. if (group != undefined) {
  273. //超过最大高度了则另起一列
  274. if (y + height + 15 > imageHeight) {
  275. y = startY;
  276. x += width;
  277. drawText(x, (y += height), title);
  278. }
  279. const content =
  280. group.number +
  281. "(" +
  282. group.titleString.join(",") +
  283. ")" +
  284. " " +
  285. group.score +
  286. (store.pageInputs["/image-download"].showSubScore
  287. ? ":" + group.subScores.join(",")
  288. : "") +
  289. " " +
  290. group.markerString.join(",") +
  291. " " +
  292. " "; //+group.headerString.join(",");
  293. width = Math.max(width, content.length * fontSize);
  294. drawText(x, (y += height), content);
  295. }
  296. }
  297. }
  298. }
  299. }
  300. //显示评卷标记
  301. if (student.tags != undefined && student.tags[index] != undefined) {
  302. const fontSize = 50;
  303. const height = fontSize + 10;
  304. // imgData.font(fontFile, fontSize).fill(color);
  305. const tags = student.tags[index];
  306. for (let i = 0; i < tags.length; i++) {
  307. const tag = tags[i];
  308. if (
  309. tag.content != undefined &&
  310. (!tag.hide || canShowDouble) &&
  311. !tag.forceHide
  312. ) {
  313. let top = tag.top;
  314. const c =
  315. tag.userId == 0
  316. ? color
  317. : tag.userRole && tag.userRole !== "MARKER"
  318. ? headerColorMap[tag.groupNumber + ""][tag.userId + ""]
  319. : colorMap[tag.groupNumber + ""][tag.userId + ""];
  320. imgData.font(fontFile, fontSize).fill(c);
  321. for (let j = 0; j < tag.content.length; j++) {
  322. drawText(tag.left, top, tag.content[j]);
  323. top += height;
  324. }
  325. }
  326. }
  327. }
  328. return new Promise((resolve, reject) => {
  329. if (onlyUsePdf) {
  330. imgData.toBase64("jpg", true, function (err: any, base64: any) {
  331. if (err) {
  332. reject(err);
  333. } else {
  334. resolve(base64);
  335. }
  336. });
  337. } else {
  338. mkdirp.sync(path.dirname(file));
  339. imgData.write(file, (error) => {
  340. if (error) {
  341. // logger.error("add watermark error: " + file);
  342. // logger.error(error);
  343. reject(error);
  344. } else {
  345. // resolve(true);
  346. resolve(file);
  347. }
  348. });
  349. }
  350. });
  351. }
  352. export async function saveImage(
  353. store: Store,
  354. imageData: ArrayBuffer,
  355. filePath: string[],
  356. onlyUsePdf = false
  357. ): Promise<any> {
  358. const file = path.join(...filePath);
  359. // console.log("saveImage file:", file);
  360. if (store.pageInputs["/image-download"].append && fs.existsSync(file)) {
  361. console.log(file + " already exists");
  362. return true;
  363. }
  364. return new Promise((resolve, reject) => {
  365. if (onlyUsePdf) {
  366. const buffer = Buffer.from(imageData, "base64");
  367. const base64Str = "data:image/jpg;base64," + buffer.toString("base64");
  368. // const base64Str = arrayBufferToBase64Img(imageData);
  369. resolve(base64Str);
  370. } else {
  371. const image = Buffer.from(imageData);
  372. mkdirp.sync(path.dirname(file));
  373. fs.writeFile(file, image, (error) => {
  374. if (error) {
  375. reject(error);
  376. } else {
  377. // resolve(true);
  378. resolve(file);
  379. }
  380. });
  381. }
  382. });
  383. }
  384. export function existsImage(pathSepArray: string[]): boolean {
  385. return fs.existsSync(path.join(...pathSepArray));
  386. }