ZipHandleHelper.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. using ICSharpCode.SharpZipLib.Checksum;
  2. using ICSharpCode.SharpZipLib.Zip;
  3. using PaintDotNet.Base.Functionodel;
  4. using PaintDotNet.Base.SettingModel;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Drawing;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. using System.Windows.Forms;
  13. using System.Xml.Serialization;
  14. using static PaintDotNet.Base.Functionodel.ZipXmlModel;
  15. namespace PaintDotNet.Base.CommTool
  16. {
  17. /// <summary>
  18. /// 操作压缩包
  19. /// </summary>
  20. public class ZipHandleHelper
  21. {
  22. public string zipName;
  23. private ZipFile zipFile;
  24. public ZipHandleHelper(string fileName)
  25. {
  26. this.zipName = fileName;
  27. if (zipName != null)
  28. zipFile = new ZipFile(File.OpenRead(zipName), true);
  29. }
  30. /// <summary>
  31. /// 从压缩包获取图片序列xml文件
  32. /// </summary>
  33. /// <returns></returns>
  34. public ZipXmlModel GetXmlFromZip()
  35. {
  36. if (zipFile != null)
  37. {
  38. ZipEntry zipEntry = zipFile.GetEntry("z-index.xml");//固定的xml文件名
  39. if (zipEntry == null)
  40. return null;
  41. using (Stream stream = zipFile.GetInputStream(zipEntry))
  42. {
  43. StreamReader streamReader = new StreamReader(stream);
  44. string xmlNotes = streamReader.ReadToEnd();
  45. ZipXmlModel zipXmlModel = XmlSerializeHelper.DESerializer<ZipXmlModel>(xmlNotes);
  46. streamReader.Dispose();
  47. return zipXmlModel;
  48. }
  49. }
  50. else
  51. return null;
  52. }
  53. /// <summary>
  54. /// 从压缩包获取标注和测量的xml
  55. /// </summary>
  56. /// <param name="picName"></param>
  57. /// <returns></returns>
  58. public PicConfigModel GetImageXmlFromZip()
  59. {
  60. if (zipFile != null)
  61. {
  62. ZipEntry zipEntry = zipFile.GetEntry("labelandmeasure.xml");//固定的标注和测量的xml
  63. if (zipEntry == null)
  64. return null;
  65. using (Stream stream = zipFile.GetInputStream(zipEntry))
  66. {
  67. StreamReader streamReader = new StreamReader(stream);
  68. string xmlNotes = streamReader.ReadToEnd();
  69. PicConfigModel picConfigModel = XmlSerializeHelper.DESerializer<PicConfigModel>(xmlNotes);
  70. streamReader.Dispose();
  71. return picConfigModel;
  72. }
  73. }
  74. else
  75. return null;
  76. }
  77. /// <summary>
  78. /// 从压缩包获取指定图片
  79. /// </summary>
  80. /// <param name="picName"></param>
  81. /// <returns></returns>
  82. public Image GetPicFromZip(string picName)
  83. {
  84. ZipInputStream inputStream = new ZipInputStream(File.OpenRead(zipName));
  85. ZipEntry zipEntry = null;
  86. while ((zipEntry = inputStream.GetNextEntry()) != null)
  87. {
  88. if (zipEntry.Name == @"images/" + picName)
  89. {
  90. long size = zipEntry.Size;
  91. byte[] data = new byte[size];
  92. while (true)
  93. {
  94. size = inputStream.Read(data, 0, data.Length);
  95. if (size <= 0)
  96. break;
  97. }
  98. MemoryStream ms = new MemoryStream(data);
  99. Image image = Image.FromStream(ms);
  100. ms.Dispose();
  101. return image;
  102. }
  103. }
  104. return null;
  105. }
  106. /// <summary>
  107. /// 从压缩包删除指定图片
  108. /// </summary>
  109. /// <param name="picName"></param>
  110. /// <returns></returns>
  111. public bool DeletePicFromZip(string picName)
  112. {
  113. if(zipFile != null)
  114. {
  115. ZipEntry zipEntry = zipFile.GetEntry(@"images/" + picName);
  116. try
  117. {
  118. zipFile.BeginUpdate();
  119. zipFile.Delete(zipEntry);
  120. zipFile.CommitUpdate();//有时会报错,不清楚原因
  121. return true;
  122. }
  123. catch (Exception)
  124. {
  125. }
  126. }
  127. return false;
  128. }
  129. /// <summary>
  130. /// 修改压缩包中的图片序列xml
  131. /// </summary>
  132. /// <param name="zipXmlModel"></param>
  133. public bool ModifyXmlNodes(ZipXmlModel zipXmlModel)
  134. {
  135. if (zipFile != null)
  136. {
  137. string xmlNotes = XmlSerializeHelper.XmlSerialize<ZipXmlModel>(zipXmlModel);
  138. try
  139. {
  140. zipFile.BeginUpdate();
  141. zipFile.Add(new StateDataSource(xmlNotes), "z-index.xml");
  142. zipFile.CommitUpdate();//有时会报错,不清楚原因
  143. return true;
  144. }
  145. catch(Exception)
  146. {
  147. }
  148. }
  149. return false;
  150. }
  151. /// <summary>
  152. /// 修改压缩包中的标注和测量xml
  153. /// </summary>
  154. /// <param name="zipXmlModel"></param>
  155. /// <returns></returns>
  156. public bool ModifyLabelAndMeasureXml(PicConfigModel picConfigModel)
  157. {
  158. if (zipFile != null)
  159. {
  160. string xmlNotes = XmlSerializeHelper.XmlSerialize<PicConfigModel>(picConfigModel);
  161. try
  162. {
  163. zipFile.BeginUpdate();
  164. zipFile.Add(new StateDataSource(xmlNotes), "labelandmeasure.xml");
  165. zipFile.CommitUpdate();//有时会报错,不清楚原因
  166. return true;
  167. }
  168. catch (Exception)
  169. {
  170. }
  171. }
  172. return false;
  173. }
  174. /// <summary>
  175. /// 创建带xml和图片的新zip包
  176. /// </summary>
  177. /// <param name="zipPath">zip包存放的路径名称</param>
  178. /// <param name="imageDirectory">要打包的图片文件夹路径</param>
  179. /// <returns></returns>
  180. public static string CompressedZipPackage(string imageDirectory)
  181. {
  182. string[] fileNames = Directory.GetFiles(imageDirectory);
  183. if(fileNames.Count() == 0)
  184. {
  185. MessageBox.Show("拍摄文件夹不存在或没有内容,打包失败");
  186. return null;
  187. }
  188. //判断是否是图片对象
  189. List<string> imageList = new List<string>();
  190. foreach(string fileName in fileNames)
  191. {
  192. try
  193. {
  194. //本来是用来保证是图片的,但是太慢了。
  195. //可以考虑读二进制的数据判断格式,但是麻烦
  196. //暂时用文件名判断代替
  197. //Image image = Image.FromFile(fileName);
  198. if (!Path.GetExtension(fileName).Equals(".xml"))
  199. {
  200. imageList.Add(fileName);
  201. }
  202. }
  203. catch(Exception)
  204. {
  205. }
  206. }
  207. if(imageList.Count == 0)
  208. {
  209. MessageBox.Show("拍摄文件夹内没有图片文件,打包失败");
  210. return null;
  211. }
  212. //zip图片排序的xml
  213. ZipXmlModel zipXmlModel = new ZipXmlModel();
  214. zipXmlModel.picNameList = new List<PicName>();
  215. //zip标注和测量的xml,不清楚初次创建是否需要添加其他信息
  216. PicConfigModel picConfigModel = new PicConfigModel();
  217. picConfigModel.hardware = new PicConfigModel.Hardware();
  218. picConfigModel.hardware.microscope = "显微镜";
  219. picConfigModel.hardware.objective = "物镜";
  220. picConfigModel.hardware.magnificationChanger = "变倍器";
  221. picConfigModel.hardware.exposureTime = "曝光时间";
  222. //存放压缩包的路径
  223. if (!Directory.Exists(Application.StartupPath + "\\temp"))
  224. Directory.CreateDirectory(Application.StartupPath + "\\temp");
  225. string zipPath = Application.StartupPath + "\\temp\\图像采集-Z轴扫描-" + DateTime.Now.ToString("HHmmss") + ".tga";
  226. try
  227. {
  228. using (ZipOutputStream zipOutputStream = new ZipOutputStream(File.Create(zipPath)))
  229. {
  230. zipOutputStream.SetLevel(6);//压缩等级1-9
  231. foreach (string imageName in imageList)
  232. {
  233. //图片名称添加到xml中
  234. PicName onePicName = new PicName();
  235. onePicName.name = Path.GetFileName(imageName);
  236. zipXmlModel.picNameList.Add(onePicName);
  237. using (FileStream fs = File.OpenRead(imageName))
  238. {
  239. byte[] buffer = new byte[4 * 1024];//缓冲区,每次操作大小
  240. string newName = "";
  241. newName = @"images/" + Path.GetFileName(imageName);
  242. ZipEntry entry = new ZipEntry(newName);//创建压缩包内的文件
  243. entry.DateTime = DateTime.Now;//文件创建时间
  244. zipOutputStream.PutNextEntry(entry);//将文件写入压缩包
  245. int sourceBytes;
  246. do
  247. {
  248. sourceBytes = fs.Read(buffer, 0, buffer.Length);//读取文件内容(1次读4M,写4M)
  249. zipOutputStream.Write(buffer, 0, sourceBytes);//将文件内容写入压缩相应的文件
  250. } while (sourceBytes > 0);
  251. }
  252. }
  253. zipOutputStream.CloseEntry();
  254. }
  255. //zipout的流对象未找到向zip包内添加非本地文件的方法
  256. //固先将图片打包到zip中,然后使用zipfile对象添加两个xml
  257. using (ZipFile zFile = new ZipFile(File.OpenRead(zipPath), true))
  258. {
  259. string xmlNotes = XmlSerializeHelper.XmlSerialize<ZipXmlModel>(zipXmlModel);
  260. string labelAndMeasureNotes = XmlSerializeHelper.XmlSerialize<PicConfigModel>(picConfigModel);
  261. zFile.BeginUpdate();
  262. zFile.Add(new StateDataSource(xmlNotes), "z-index.xml");
  263. zFile.Add(new StateDataSource(labelAndMeasureNotes), "labelandmeasure.xml");
  264. zFile.CommitUpdate();//有时会报错,不清楚原因
  265. }
  266. }
  267. catch(Exception)
  268. {
  269. if (File.Exists(zipPath))
  270. File.Delete(zipPath);
  271. MessageBox.Show("打包保存失败");
  272. return "";
  273. }
  274. return zipPath;
  275. }
  276. #region [生成压缩包]
  277. /// <summary>
  278. ///
  279. /// </summary>
  280. public static void createZip(string fileName, string outFileName)
  281. {
  282. if (fileName[fileName.Length - 1] != Path.DirectorySeparatorChar)
  283. {
  284. fileName += Path.DirectorySeparatorChar;
  285. }
  286. ZipOutputStream outstream = new ZipOutputStream(File.Create(outFileName));
  287. outstream.SetLevel(6);
  288. zip(fileName, outstream, fileName);
  289. outstream.Finish();
  290. outstream.Close();
  291. }
  292. public static void zip(string strFile, ZipOutputStream outstream, string staticFile)
  293. {
  294. if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar)
  295. {
  296. strFile += Path.DirectorySeparatorChar;
  297. }
  298. Crc32 crc = new Crc32();
  299. //获取指定目录下所有文件和子目录文件名称
  300. string[] filenames = Directory.GetFileSystemEntries(strFile);
  301. //遍历文件
  302. foreach (string file in filenames)
  303. {
  304. if (Directory.Exists(file))
  305. {
  306. zip(file, outstream, staticFile);
  307. }
  308. //否则,直接压缩文件
  309. else
  310. {
  311. //打开文件
  312. FileStream fs = File.OpenRead(file);
  313. //定义缓存区对象
  314. byte[] buffer = new byte[fs.Length];
  315. //通过字符流,读取文件
  316. fs.Read(buffer, 0, buffer.Length);
  317. //得到目录下的文件(比如:D:\Debug1\test),test
  318. string tempfile = file.Substring(staticFile.LastIndexOf("\\") + 1);
  319. ZipEntry entry = new ZipEntry(tempfile);
  320. entry.DateTime = DateTime.Now;
  321. entry.Size = fs.Length;
  322. fs.Close();
  323. crc.Reset();
  324. crc.Update(buffer);
  325. entry.Crc = crc.Value;
  326. outstream.PutNextEntry(entry);
  327. //写文件
  328. outstream.Write(buffer, 0, buffer.Length);
  329. }
  330. }
  331. }
  332. #endregion
  333. #region [解压压缩包]
  334. /// <summary>
  335. ///
  336. /// </summary>
  337. public static bool decompressionZip(string TargetFile, string fileDir)
  338. {
  339. string rootFile = "";
  340. bool success = false;
  341. try
  342. {
  343. //读取压缩文件(zip文件),准备解压缩
  344. ZipInputStream inputstream = new ZipInputStream(File.OpenRead(TargetFile.Trim()));
  345. ZipEntry entry;
  346. string path = fileDir;
  347. //解压出来的文件保存路径
  348. string rootDir = "";
  349. //根目录下的第一个子文件夹的名称
  350. while ((entry = inputstream.GetNextEntry()) != null)
  351. {
  352. rootDir = Path.GetDirectoryName(entry.Name);
  353. //得到根目录下的第一级子文件夹的名称
  354. if (rootDir.IndexOf("\\") >= 0)
  355. {
  356. rootDir = rootDir.Substring(0, rootDir.IndexOf("\\") + 1);
  357. }
  358. string dir = Path.GetDirectoryName(entry.Name);
  359. //得到根目录下的第一级子文件夹下的子文件夹名称
  360. string fileName = Path.GetFileName(entry.Name);
  361. //根目录下的文件名称
  362. if (dir != "")
  363. {
  364. //创建根目录下的子文件夹,不限制级别
  365. if (!Directory.Exists(fileDir + "\\" + dir))
  366. {
  367. path = fileDir + "\\" + dir;
  368. //在指定的路径创建文件夹
  369. Directory.CreateDirectory(path);
  370. }
  371. }
  372. else if (dir == "" && fileName != "")
  373. {
  374. //根目录下的文件
  375. path = fileDir;
  376. rootFile = fileName;
  377. }
  378. else if (dir != "" && fileName != "")
  379. {
  380. //根目录下的第一级子文件夹下的文件
  381. if (dir.IndexOf("\\") > 0)
  382. {
  383. //指定文件保存路径
  384. path = fileDir + "\\" + dir;
  385. }
  386. }
  387. if (dir == rootDir)
  388. {
  389. //判断是不是需要保存在根目录下的文件
  390. path = fileDir + "\\" + rootDir;
  391. }
  392. //以下为解压zip文件的基本步骤
  393. //基本思路:遍历压缩文件里的所有文件,创建一个相同的文件
  394. if (fileName != String.Empty)
  395. {
  396. FileStream fs = File.Create(path + "\\" + fileName);
  397. int size = 2048;
  398. byte[] data = new byte[2048];
  399. while (true)
  400. {
  401. size = inputstream.Read(data, 0, data.Length);
  402. if (size > 0)
  403. {
  404. fs.Write(data, 0, size);
  405. }
  406. else
  407. {
  408. break;
  409. }
  410. }
  411. fs.Close();
  412. }
  413. }
  414. inputstream.Close();
  415. success = true;
  416. }
  417. catch (Exception ex)
  418. {
  419. }
  420. return success;
  421. }
  422. #endregion
  423. /// <summary>
  424. /// 自定义实现IStaticDataSource接口的类
  425. /// </summary>
  426. class StateDataSource : IStaticDataSource
  427. {
  428. string source;
  429. public StateDataSource(string source)
  430. {
  431. this.source = source;
  432. }
  433. public Stream GetSource()
  434. {
  435. byte[] array = Encoding.UTF8.GetBytes(source);//使用asc2会中文乱码
  436. MemoryStream stream = new MemoryStream(array);
  437. return stream;
  438. }
  439. }
  440. }
  441. }