ImageControl.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. using Common;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Reflection;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using System.Drawing;
  13. using com.hnshituo.core.webapp.vo;
  14. namespace MeterPlugInLibrary
  15. {
  16. /// <summary>
  17. /// 在进入系统后,需开启这个线程用于每10秒上传一次图片到ftp服务器
  18. /// 在退出系统后,需关闭这个线程
  19. /// </summary>
  20. public class ImageControl
  21. {
  22. SFTPHelper ftp_helper;
  23. VSFTPHelper vftp_helper;
  24. Thread task;
  25. public ImageControl()
  26. {
  27. Init();
  28. }
  29. private void Init()
  30. {
  31. switch (AppConfigCache.ftpType)
  32. {
  33. case "0":
  34. ftp_helper = new SFTPHelper(AppConfigCache.ftpIp, AppConfigCache.ftpPort, AppConfigCache.ftpUid, AppConfigCache.ftpPwd);
  35. break;
  36. case "1":
  37. //vftp_helper = new VSFTPHelper();
  38. vftp_helper = new VSFTPHelper(AppConfigCache.ftpIp, AppConfigCache.ftpUid, AppConfigCache.ftpPwd);
  39. break;
  40. }
  41. }
  42. /// <summary>
  43. /// 启动TFP上传线程
  44. /// </summary>
  45. public void Start()
  46. {
  47. if (task == null)
  48. {
  49. task = new Thread(new ThreadStart(Doworks));
  50. task.Start();
  51. }
  52. }
  53. public void Stop()
  54. {
  55. if (task != null)
  56. {
  57. task.Abort();
  58. task = null;
  59. }
  60. }
  61. private void Doworks()
  62. {
  63. do
  64. {
  65. int waitSecs = 10000;
  66. int i = 0;
  67. try
  68. {
  69. string sPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "imgShort\\";
  70. i = 1;
  71. string picPath = Path.Combine(sPath, "tempImg");
  72. i = 2;
  73. ArrayList UnZipedFiles = GetFiles(picPath, ".jpg");//tmp!
  74. i = 3;
  75. //ZipFiles(UnZipedFiles); //2021年3月2日不再进行图片压缩,直接存到正式文件夹formalImg中
  76. i = 4;
  77. //获取正式目录文件进行上传
  78. ArrayList files = GetFiles(sPath + "formalImg", ".jpg");
  79. i = 5;
  80. UploadFiles(files);
  81. i = 6;
  82. //删除正式目录文件
  83. if (Directory.Exists(sPath))//如果不存在就不用删
  84. {
  85. //RemoveRedundantDir(Path.Combine(sPath, "formalImg"), 0);
  86. }
  87. i = 7;
  88. }
  89. catch (Exception exp)
  90. {
  91. WriteLog("ImageControl.Doworks在" + i + "位置异常,异常信息:" + exp.Message);
  92. }
  93. finally
  94. {
  95. Thread.Sleep(waitSecs);
  96. }
  97. } while (true);
  98. }
  99. private void RemoveRedundantDir(string _path, int deep)
  100. {
  101. DirectoryInfo theFolder = new DirectoryInfo(_path);
  102. DirectoryInfo[] dirInfos = theFolder.GetDirectories();
  103. if (dirInfos != null && dirInfos.Count() > 0)
  104. {
  105. foreach (DirectoryInfo di in dirInfos)
  106. {
  107. RemoveRedundantDir(di.FullName, deep + 1);
  108. }
  109. }
  110. try
  111. {
  112. if (deep == 0) return;
  113. FileInfo[] fileinfos = theFolder.GetFiles();
  114. if (fileinfos == null || fileinfos.Count() == 0)
  115. {
  116. DateTime dt;
  117. if (DateTime.TryParseExact(theFolder.Name, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.AllowWhiteSpaces, out dt))
  118. {
  119. if (TimeSpan.FromTicks(DateTime.Today.Ticks).Subtract(TimeSpan.FromTicks(dt.Date.Ticks)).TotalDays > 1)
  120. {
  121. Directory.Delete(_path);
  122. }
  123. }
  124. }
  125. }
  126. catch { }
  127. }
  128. private void ZipFiles(ArrayList UnzipedFiles)
  129. {
  130. ImageZip iz = new ImageZip();
  131. if (UnzipedFiles == null || UnzipedFiles.Count == 0) return;
  132. foreach (string fn in UnzipedFiles)
  133. {
  134. if (string.IsNullOrEmpty(fn)) continue;
  135. if (!File.Exists(fn)) continue;
  136. //临时目录图片压缩后存储与正式目录
  137. string jpgFile = fn.Replace("tempImg", "formalImg");
  138. Image img = ImageZip.BytesToBitmap(ImageZip.ZipImageByte(fn));
  139. if (img != null)
  140. {
  141. //iz.ResourceImage = img;
  142. //压缩图片并保存
  143. //iz.GetReducedImage(AppConfigCache.imgWidth, AppConfigCache.imgHeight).Save(jpgFile);
  144. img.Save(jpgFile);
  145. File.Delete(fn);//删除临时目录数据
  146. }
  147. else
  148. {
  149. iz.ResourceImage = img;
  150. //压缩图片并保存
  151. iz.GetReducedImage(400, 400).Save(jpgFile);
  152. //File.Move(fn, jpgFile);
  153. }
  154. }
  155. }
  156. private ArrayList GetFiles(string _dirPath, string extensionName)
  157. {
  158. ArrayList files = new ArrayList();
  159. if (!Directory.Exists(_dirPath)) return null;
  160. DirectoryInfo theFolder = new DirectoryInfo(_dirPath);
  161. FileInfo[] fileinfos = theFolder.GetFiles("*" + extensionName);
  162. if (fileinfos != null && fileinfos.Count() > 0)
  163. {
  164. foreach (FileInfo fi in fileinfos)
  165. {
  166. files.Add(fi.FullName);
  167. }
  168. }
  169. DirectoryInfo[] dirInfos = theFolder.GetDirectories();
  170. if (dirInfos != null && dirInfos.Count() > 0)
  171. {
  172. foreach (DirectoryInfo di in dirInfos)
  173. {
  174. files.AddRange(GetFiles(di.FullName, extensionName));
  175. }
  176. }
  177. return files;
  178. }
  179. // 后台刷FTP线程调用
  180. private void UploadFiles(ArrayList files)
  181. {
  182. if ("0".Equals(AppConfigCache.ftpType))
  183. {
  184. if (files == null || files.Count == 0 || ftp_helper == null) return;
  185. }
  186. else
  187. {
  188. if (files == null || files.Count == 0 || vftp_helper == null) return;
  189. }
  190. if (AppConfigCache.ftpType == "0")
  191. {
  192. if (!ftp_helper.Connect()) return;
  193. }
  194. string localpath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, @"imgShort\formalImg\"));
  195. string lastpath = AppConfigCache.ftpPath;
  196. foreach (string _filepath in files)
  197. {
  198. try
  199. {
  200. //计算ftp相对路径
  201. Uri u1 = new Uri(localpath, UriKind.Absolute);
  202. Uri u2 = new Uri(Path.GetDirectoryName(_filepath), UriKind.Absolute);
  203. Uri u3 = u1.MakeRelativeUri(u2);//u2相对于u1的uri
  204. //string ftpdir = Path.Combine(AppConfigCache.ftpPath + "/", u3.ToString());
  205. string ftpdir = Path.Combine(AppConfigCache.ftpPath, u3.ToString().Replace("../", ""));
  206. //验证文件名是否合法
  207. string filename = Path.GetFileName(_filepath);
  208. //filename : 计量作业编号_序号.jpg 计量作业编号:计量点编号+年月日时分秒
  209. MeterWorkImage ci = ParseFileName(filename, ftpdir.Replace("formalImg", DateTime.Now.ToString("yyyy-MM-dd")));
  210. if (ci == null) continue;
  211. switch (AppConfigCache.ftpType)
  212. {
  213. case "0":
  214. {
  215. if (ftpdir != lastpath)
  216. {
  217. ftp_helper.CreateDirectory(ftpdir);
  218. }
  219. ftp_helper.Put(_filepath, ftpdir, filename);
  220. };
  221. break;
  222. case "1":
  223. {
  224. vftp_helper.FtpUp(_filepath);
  225. }; break;
  226. }
  227. lastpath = ftpdir;
  228. //存储计量数据的时候,实际上是先将计量数据及图片路径
  229. MeterWorkImageService service = new MeterWorkImageService();
  230. RESTfulResult<string> rm = service.doSaveWf(ci); //db.doOption<string>("MeterWorkImageService", "doSaveWf", new object[] { ci }, 1);
  231. if (rm.Succeed)
  232. {
  233. WriteLog(string.Format("更新图片记录[{0}]:{1}", ci.actualFirstNo, filename));
  234. File.Delete(_filepath);
  235. }
  236. else
  237. {
  238. WriteLog(string.Format("上传图片失败! [{0}]\n{1}", ci.actualFirstNo, filename));
  239. }
  240. //
  241. }
  242. catch (Exception exp)
  243. {
  244. WriteLog(string.Format("上传图片失败! [{0}]\n{1}", _filepath, exp.Message));
  245. }
  246. }
  247. if (vftp_helper == null)
  248. {
  249. ftp_helper.Disconnect();
  250. }
  251. }
  252. /// <summary>
  253. /// 验证图片名称
  254. /// </summary>
  255. /// <param name="filename">计量点编号_作业编号_序号.jpg</param>
  256. /// <param name="ftpdir"></param>
  257. /// <returns></returns>
  258. private MeterWorkImage ParseFileName(string filename, string ftpdir)
  259. {
  260. MeterWorkImage ci = new MeterWorkImage();
  261. filename = Path.GetFileName(filename);
  262. string[] segs = filename.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
  263. if (segs == null || segs.Count() < 3)
  264. {
  265. WriteLog("文件名不符合要求! (3段命名):" + filename);
  266. return null;
  267. }
  268. int seq;
  269. //int icar_seq = 0;
  270. //int.TryParse(car_seq, out icar_seq);
  271. string[] seqs = segs[2].Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
  272. if (seqs == null || seqs.Count() == 0 || !int.TryParse(seqs[0], out seq))
  273. {
  274. WriteLog("文件名不符合要求! (序号不正确):" + filename);
  275. return null;
  276. }
  277. string fullfilename = ftpdir + "/" + filename;
  278. fullfilename = fullfilename.Replace("//", "/").Replace("//", "/");
  279. PropertyInfo pi = null;
  280. try
  281. {
  282. pi = ci.GetType().GetProperty(string.Format("imageFile{0}", seq));
  283. pi.SetValue(ci, fullfilename.Replace("/pub", ""));
  284. }
  285. catch
  286. {
  287. WriteLog("文件名不符合要求! (序号超出数据库要求):" + fullfilename);
  288. return null;
  289. }
  290. //ci.image_time = DateTime.ParseExact(segs[0].Substring(segs[0].Length - 14, 14), "yyyyMMddHHmmss", CultureInfo.CurrentCulture);
  291. ci.actualFirstNo = segs[1];
  292. return ci;
  293. }
  294. public void Release()
  295. {
  296. try
  297. {
  298. if (ftp_helper != null)
  299. {
  300. ftp_helper.Disconnect();
  301. }
  302. if (task != null)
  303. {
  304. task.Abort();
  305. task = null;
  306. }
  307. }
  308. catch { }
  309. }
  310. private static void WriteLog(string str)
  311. {
  312. // 20220925 By BourneCao 暂时屏蔽语音播放日志
  313. return;
  314. try
  315. {
  316. string m_szRunPath;
  317. m_szRunPath = System.Environment.CurrentDirectory;
  318. if (System.IO.Directory.Exists(m_szRunPath + "\\log") == false)
  319. {
  320. System.IO.Directory.CreateDirectory(m_szRunPath + "\\log");
  321. }
  322. string strDate = System.DateTime.Now.ToString("yyyyMMdd");
  323. string strPathFile = m_szRunPath + "\\log\\" + strDate;
  324. if (!Directory.Exists(strPathFile))//如果不存在就创建file文件夹
  325. {
  326. Directory.CreateDirectory(strPathFile);
  327. }
  328. System.IO.TextWriter tw = new System.IO.StreamWriter(strPathFile + "\\FTP_image_" + strDate + ".log", true);
  329. tw.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  330. tw.WriteLine(str);
  331. tw.WriteLine("\r\n");
  332. tw.Close();
  333. }
  334. catch { }
  335. }
  336. //*/
  337. }
  338. }