ZipHandleHelper.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. using ICSharpCode.SharpZipLib.Checksum;
  2. using ICSharpCode.SharpZipLib.Zip;
  3. using SmartCoalApplication.Base.CommTool;
  4. using SmartCoalApplication.Base.Functionodel;
  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 SmartCoalApplication.Base.Functionodel.ZipXmlModel;
  15. namespace SmartCoalApplication.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. /// <summary>
  277. /// 自定义实现IStaticDataSource接口的类
  278. /// </summary>
  279. class StateDataSource : IStaticDataSource
  280. {
  281. string source;
  282. public StateDataSource(string source)
  283. {
  284. this.source = source;
  285. }
  286. public Stream GetSource()
  287. {
  288. byte[] array = Encoding.UTF8.GetBytes(source);//使用asc2会中文乱码
  289. MemoryStream stream = new MemoryStream(array);
  290. return stream;
  291. }
  292. }
  293. #region [生成压缩包]
  294. /// <summary>
  295. ///
  296. /// </summary>
  297. public static void createZip(string fileName, string outFileName)
  298. {
  299. if (fileName[fileName.Length - 1] != Path.DirectorySeparatorChar)
  300. {
  301. fileName += Path.DirectorySeparatorChar;
  302. }
  303. ZipOutputStream outstream = new ZipOutputStream(File.Create(outFileName));
  304. outstream.SetLevel(6);
  305. zip(fileName, outstream, fileName);
  306. outstream.Finish();
  307. outstream.Close();
  308. }
  309. public static void zip(string strFile, ZipOutputStream outstream, string staticFile)
  310. {
  311. if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar)
  312. {
  313. strFile += Path.DirectorySeparatorChar;
  314. }
  315. Crc32 crc = new Crc32();
  316. //获取指定目录下所有文件和子目录文件名称
  317. string[] filenames = Directory.GetFileSystemEntries(strFile);
  318. //遍历文件
  319. foreach (string file in filenames)
  320. {
  321. if (Directory.Exists(file))
  322. {
  323. zip(file, outstream, staticFile);
  324. }
  325. //否则,直接压缩文件
  326. else
  327. {
  328. //打开文件
  329. FileStream fs = File.OpenRead(file);
  330. //定义缓存区对象
  331. byte[] buffer = new byte[fs.Length];
  332. //通过字符流,读取文件
  333. fs.Read(buffer, 0, buffer.Length);
  334. //得到目录下的文件(比如:D:\Debug1\test),test
  335. string tempfile = file.Substring(staticFile.LastIndexOf("\\") + 1);
  336. ZipEntry entry = new ZipEntry(tempfile);
  337. entry.DateTime = DateTime.Now;
  338. entry.Size = fs.Length;
  339. fs.Close();
  340. crc.Reset();
  341. crc.Update(buffer);
  342. entry.Crc = crc.Value;
  343. outstream.PutNextEntry(entry);
  344. //写文件
  345. outstream.Write(buffer, 0, buffer.Length);
  346. }
  347. }
  348. }
  349. #endregion
  350. #region [解压压缩包]
  351. /// <summary>
  352. ///
  353. /// </summary>
  354. public static bool decompressionZip(string TargetFile, string fileDir)
  355. {
  356. string rootFile = "";
  357. bool success = false;
  358. try
  359. {
  360. //读取压缩文件(zip文件),准备解压缩
  361. ZipInputStream inputstream = new ZipInputStream(File.OpenRead(TargetFile.Trim()));
  362. ZipEntry entry;
  363. string path = fileDir;
  364. //解压出来的文件保存路径
  365. string rootDir = "";
  366. //根目录下的第一个子文件夹的名称
  367. while ((entry = inputstream.GetNextEntry()) != null)
  368. {
  369. rootDir = Path.GetDirectoryName(entry.Name);
  370. //得到根目录下的第一级子文件夹的名称
  371. if (rootDir.IndexOf("\\") >= 0)
  372. {
  373. rootDir = rootDir.Substring(0, rootDir.IndexOf("\\") + 1);
  374. }
  375. string dir = Path.GetDirectoryName(entry.Name);
  376. //得到根目录下的第一级子文件夹下的子文件夹名称
  377. string fileName = Path.GetFileName(entry.Name);
  378. //根目录下的文件名称
  379. if (dir != "")
  380. {
  381. //创建根目录下的子文件夹,不限制级别
  382. if (!Directory.Exists(fileDir + "\\" + dir))
  383. {
  384. path = fileDir + "\\" + dir;
  385. //在指定的路径创建文件夹
  386. Directory.CreateDirectory(path);
  387. }
  388. }
  389. else if (dir == "" && fileName != "")
  390. {
  391. //根目录下的文件
  392. path = fileDir;
  393. rootFile = fileName;
  394. }
  395. else if (dir != "" && fileName != "")
  396. {
  397. //根目录下的第一级子文件夹下的文件
  398. if (dir.IndexOf("\\") > 0)
  399. {
  400. //指定文件保存路径
  401. path = fileDir + "\\" + dir;
  402. }
  403. }
  404. if (dir == rootDir)
  405. {
  406. //判断是不是需要保存在根目录下的文件
  407. path = fileDir + "\\" + rootDir;
  408. }
  409. //以下为解压zip文件的基本步骤
  410. //基本思路:遍历压缩文件里的所有文件,创建一个相同的文件
  411. if (fileName != String.Empty)
  412. {
  413. FileStream fs = File.Create(path + "\\" + fileName);
  414. int size = 2048;
  415. byte[] data = new byte[2048];
  416. while (true)
  417. {
  418. size = inputstream.Read(data, 0, data.Length);
  419. if (size > 0)
  420. {
  421. fs.Write(data, 0, size);
  422. }
  423. else
  424. {
  425. break;
  426. }
  427. }
  428. fs.Close();
  429. }
  430. }
  431. inputstream.Close();
  432. success = true;
  433. }
  434. catch (Exception ex)
  435. {
  436. }
  437. return success;
  438. }
  439. #endregion
  440. }
  441. }