Program.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. using ImageMagick;
  2. using System.IO.Compression;
  3. using SevenZip;
  4. using CompressionLevel = SevenZip.CompressionLevel;
  5. using CompressionMethod = SevenZip.CompressionMethod;
  6. using ImageMagick.Formats;
  7. namespace WebPnCbzMaker
  8. {
  9. internal class Program
  10. {
  11. private static void Main(string[] args)
  12. {
  13. Console.WriteLine("Hello, World!");
  14. SevenZipBase.SetLibraryPath(@"C:\Program Files\7-Zip\7z.dll");
  15. //input folder
  16. // $root
  17. // |- 123456-name
  18. // |- 000001.jpg or png
  19. // |- 000002.jpg or png
  20. // |- thumb.jpg or thumb.webp
  21. // |- ComicInfo.xml
  22. // |- 56789-name
  23. // |- 000001.jpg or png
  24. // |- 000002.jpg or png
  25. // |- thumb.jpg or thumb.webp
  26. // |- ComicInfo.xml
  27. //output folder
  28. // $root
  29. // |- 123456-name
  30. // |- ComicInfo.xml <- copy
  31. // |- thumb.jpg or thumb.webp <- copy
  32. // |- 123456.cbz <- create zip from [seq img:convert to webP] and [ComicInfo.xml]
  33. // |- 56789-name
  34. // |- ComicInfo.xml <- copy
  35. // |- thumb.jpg or thumb.webp <- copy
  36. // |- 56789.cbz <- create zip from [seq img:convert to webP] and [ComicInfo.xml]
  37. var inputFolder = "./In";
  38. var outputFolder = "./Out";
  39. // 遍历输入文件夹中的所有子文件夹
  40. var inDirs = Directory.GetDirectories(inputFolder);
  41. for (var index = 0; index < inDirs.Length; index++)
  42. {
  43. var dir = inDirs[index];
  44. // 获取目录名称(例如:123456-name)
  45. var folderName = Path.GetFileName(dir);
  46. Console.WriteLine($" >>> [{index + 1:0000}/{inDirs.Length:0000}] Enter folder: {folderName}");
  47. // 提取前面的数字部分作为 CBZ 文件名
  48. var folderNameDigits = folderName.Split('-', 2)[0];
  49. if (folderNameDigits.All(char.IsAsciiDigit) == false)
  50. {
  51. Console.WriteLine($"[WARN] skip folder: {folderName}");
  52. continue;
  53. }
  54. var cbzFileName = $"{folderNameDigits}.cbz";
  55. var outputPath = Path.Combine(outputFolder, folderName);
  56. var destCbzPath = Path.Combine(outputPath, cbzFileName);
  57. var cbz7MarkerPath = Path.Combine(outputPath, "WebPnCbz.7");
  58. if (File.Exists(destCbzPath))
  59. {
  60. if (File.Exists(cbz7MarkerPath))
  61. {
  62. Console.WriteLine($"[SKIP] skip folder, exist {cbzFileName} and 7");
  63. }
  64. else
  65. {
  66. //TODO: Conv cbz(zip) to webp in cbz(7z)
  67. //then TouchFile(cbz7MarkerPath);
  68. }
  69. continue;
  70. }
  71. var cbzAlreadyExistPath = Path.Combine(dir, cbzFileName);
  72. var flagFoundExistedCbz = File.Exists(cbzAlreadyExistPath);
  73. var lstFilesToCbz = new List<string>();
  74. var lstFilesCopy = new List<string>();
  75. var flagSeqExist = false;
  76. if (flagFoundExistedCbz) lstFilesCopy.Add(cbzAlreadyExistPath);
  77. foreach (var filePath in Directory.GetFiles(dir))
  78. {
  79. //ComicInfo.xml 要复制到输出目录并且也要压入归档
  80. if (Path.GetFileName(filePath).Equals("ComicInfo.xml", StringComparison.InvariantCultureIgnoreCase))
  81. {
  82. lstFilesToCbz.Add(filePath);
  83. lstFilesCopy.Add(filePath);
  84. continue;
  85. }
  86. //序列文件名压入归档
  87. var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
  88. if (fileNameWithoutExtension.Length > 0 && fileNameWithoutExtension.All(char.IsDigit))
  89. {
  90. if (flagFoundExistedCbz == false) lstFilesToCbz.Add(filePath);
  91. flagSeqExist = true;
  92. continue;
  93. }
  94. //其他直接拷贝
  95. lstFilesCopy.Add(filePath);
  96. }
  97. if (flagSeqExist == false)
  98. {
  99. Console.WriteLine($"[WARN] skip folder: {folderName}, no SEQ file found");
  100. continue;
  101. }
  102. // 创建输出文件夹
  103. Directory.CreateDirectory(outputPath);
  104. // 处理直接拷贝
  105. foreach (var copy in lstFilesCopy)
  106. {
  107. var destFilePath = Path.Combine(outputPath, Path.GetFileName(copy));
  108. if (File.Exists(destFilePath))
  109. {
  110. Console.WriteLine($"[SKIP] Copy file: {Path.GetFileName(copy)}");
  111. continue;
  112. }
  113. Console.WriteLine($"Copy file: {Path.GetFileName(copy)}");
  114. File.Copy(copy, destFilePath);
  115. }
  116. // 创建 webP 7z 作为 cbz
  117. if (flagFoundExistedCbz == false)
  118. {
  119. var dictEntries = new Dictionary<string, Stream>();
  120. Parallel.ForEach(lstFilesToCbz, toCbz =>
  121. {
  122. var bytes = File.ReadAllBytes(toCbz);
  123. try
  124. {
  125. bytes = ConvertToWebP(bytes);
  126. lock (dictEntries) dictEntries[Path.GetFileNameWithoutExtension(toCbz) + ".webp"] = new MemoryStream(bytes);
  127. Console.WriteLine($"Convert (WebP) file to archive: {Path.GetFileName(toCbz)}");
  128. }
  129. catch (Exception e)
  130. {
  131. Console.WriteLine(e);
  132. Console.WriteLine($"Add file to archive: {Path.GetFileName(toCbz)}");
  133. lock (dictEntries) dictEntries[Path.GetFileName(toCbz)] = new MemoryStream(bytes);
  134. }
  135. });
  136. Console.WriteLine($"Creating archive file: {destCbzPath}");
  137. var cbzBytes = MakeSevenZip(dictEntries);
  138. Console.WriteLine($"Writing archive file: {destCbzPath}");
  139. File.WriteAllBytes(destCbzPath, cbzBytes);
  140. }
  141. TouchFile(cbz7MarkerPath);
  142. Console.WriteLine($" <<< Leave folder: {folderName}");
  143. }
  144. Console.WriteLine("Bye, World!");
  145. }
  146. private static readonly WebPWriteDefines WebPDefines = new()
  147. {
  148. Lossless = false,
  149. Method = 6,
  150. };
  151. private static byte[] ConvertToWebP(byte[] imageBytes)
  152. {
  153. using var image = new MagickImage(imageBytes);
  154. using var ms = new MemoryStream();
  155. image.Format = MagickFormat.WebP;
  156. image.Write(ms, WebPDefines);
  157. return ms.ToArray(); // 返回 WebP 图像字节流
  158. }
  159. private static byte[] MakeSevenZip(Dictionary<string, Stream> entries)
  160. {
  161. var szc = new SevenZipCompressor();
  162. szc.ArchiveFormat = OutArchiveFormat.SevenZip;
  163. szc.CompressionLevel = CompressionLevel.Ultra;
  164. szc.CompressionMethod = CompressionMethod.Lzma2;
  165. szc.CustomParameters["s"] = "off";
  166. var outStream = new MemoryStream();
  167. szc.CompressStreamDictionary(entries, outStream);
  168. return outStream.ToArray();
  169. }
  170. /// <summary>
  171. /// 模拟 Linux 的 touch 命令。
  172. /// 如果文件不存在,则创建文件;
  173. /// 如果文件已存在,则更新文件的最后访问时间和修改时间。
  174. /// </summary>
  175. /// <param name="path">文件的路径。</param>
  176. /// <exception cref="UnauthorizedAccessException">当没有权限访问路径时抛出。</exception>
  177. /// <exception cref="IOException">当发生 I/O 错误时抛出。</exception>
  178. private static void TouchFile(string path)
  179. {
  180. try
  181. {
  182. // 如果文件存在,更新最后访问时间和修改时间。
  183. if (File.Exists(path))
  184. {
  185. File.SetLastAccessTime(path, DateTime.Now);
  186. File.SetLastWriteTime(path, DateTime.Now);
  187. }
  188. else
  189. {
  190. // 如果文件不存在,创建一个空文件。
  191. using var _ = File.Create(path);
  192. }
  193. }
  194. catch (Exception ex) when (ex is UnauthorizedAccessException || ex is IOException)
  195. {
  196. throw new InvalidOperationException($"无法 touch 文件: {path}", ex);
  197. }
  198. }
  199. }
  200. }