DocumentStitch.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. using System;
  2. using System.Collections.Specialized;
  3. using System.ComponentModel;
  4. using System.Drawing;
  5. using System.Drawing.Imaging;
  6. using System.Runtime.Serialization;
  7. using System.Windows.Forms;
  8. namespace PaintDotNet
  9. {
  10. [Serializable]
  11. public sealed class StitchDocument : IDeserializationCallback, IDisposable
  12. {
  13. public StitchSurface surface;
  14. private int width;
  15. private int height;
  16. private NameValueCollection userMetaData;
  17. [NonSerialized]
  18. private Vector<Rectangle> updateRegion;
  19. [NonSerialized]
  20. private bool dirty;
  21. [NonSerialized]
  22. private Metadata metadata = null;
  23. /// <summary>
  24. /// Gets or sets the units that are used for measuring the document's physical (printed) size.
  25. /// </summary>
  26. /// <remarks>
  27. /// If this property is set to MeasurementUnit.Pixel, then Dpu will be reset to 1.
  28. /// If this property has not been set in the image's metadata, its default value
  29. /// will be MeasurementUnit.Inch.
  30. /// If the EXIF data for the image is invalid (such as "ResolutionUnit = 0" or something),
  31. /// then the default DpuUnit will be returned.
  32. /// </remarks>
  33. public MeasurementUnit DpuUnit
  34. {
  35. get
  36. {
  37. PropertyItem[] pis = this.Metadata.GetExifValues(ExifTagID.ResolutionUnit);
  38. if (pis.Length == 0)
  39. {
  40. this.DpuUnit = DefaultDpuUnit;
  41. return DefaultDpuUnit;
  42. }
  43. else
  44. {
  45. try
  46. {
  47. ushort unit = Exif.DecodeShortValue(pis[0]);
  48. // Guard against bad data in the EXIF store
  49. switch ((MeasurementUnit)unit)
  50. {
  51. case MeasurementUnit.Pixel:
  52. case MeasurementUnit.Inch:
  53. case MeasurementUnit.Mil:
  54. case MeasurementUnit.Centimeter:
  55. case MeasurementUnit.Millimeter:
  56. case MeasurementUnit.Micron:
  57. case MeasurementUnit.Nano:
  58. return (MeasurementUnit)unit;
  59. default:
  60. this.Metadata.RemoveExifValues(ExifTagID.ResolutionUnit);
  61. return this.DpuUnit; // recursive call
  62. }
  63. }
  64. catch (Exception)
  65. {
  66. this.Metadata.RemoveExifValues(ExifTagID.ResolutionUnit);
  67. return this.DpuUnit; // recursive call
  68. }
  69. }
  70. }
  71. set
  72. {
  73. PropertyItem pi = Exif.CreateShort(ExifTagID.ResolutionUnit, (ushort)value);
  74. this.Metadata.ReplaceExifValues(ExifTagID.ResolutionUnit, new PropertyItem[1] { pi });
  75. if (value == MeasurementUnit.Pixel)
  76. {
  77. this.DpuX = 1.0;
  78. this.DpuY = 1.0;
  79. }
  80. Dirty = true;
  81. }
  82. }
  83. public static MeasurementUnit DefaultDpuUnit
  84. {
  85. get
  86. {
  87. return MeasurementUnit.Inch;
  88. }
  89. }
  90. public static double defaultDpi = 96;
  91. /// <summary>
  92. /// 1英寸 = 2.54厘米
  93. /// </summary>
  94. public static double CmPerInch = 2.54;
  95. /// <summary>
  96. /// 默认值 = dpi / 单位
  97. /// </summary>
  98. public double defaultDpcm;
  99. public const double MinimumDpu = 0.01;
  100. public const double MaximumDpu = 32767.0;
  101. public static double GetDefaultDpu(MeasurementUnit units)
  102. {
  103. double dpu;
  104. switch (units)
  105. {
  106. case MeasurementUnit.Inch:
  107. dpu = defaultDpi;
  108. break;
  109. case MeasurementUnit.Mil:
  110. dpu = defaultDpi / 1000;
  111. break;
  112. case MeasurementUnit.Centimeter:
  113. dpu = defaultDpi / CmPerInch;
  114. break;
  115. case MeasurementUnit.Millimeter:
  116. dpu = defaultDpi / CmPerInch / 10;
  117. break;
  118. case MeasurementUnit.Micron:
  119. dpu = defaultDpi / CmPerInch / 10000;
  120. break;
  121. case MeasurementUnit.Nano:
  122. dpu = defaultDpi / CmPerInch / 10000000;
  123. break;
  124. case MeasurementUnit.Pixel:
  125. dpu = 1.0;
  126. break;
  127. default:
  128. throw new InvalidEnumArgumentException("DpuUnit", (int)units, typeof(MeasurementUnit));
  129. }
  130. return dpu;
  131. }
  132. private byte[] GetDoubleAsRationalExifData(double value)
  133. {
  134. uint numerator;
  135. uint denominator;
  136. if (Math.IEEERemainder(value, 1.0) == 0)
  137. {
  138. numerator = (uint)value;
  139. denominator = 1;
  140. }
  141. else
  142. {
  143. double s = value * 1000.0;
  144. numerator = (uint)Math.Floor(s);
  145. denominator = 1000;
  146. }
  147. return Exif.EncodeRationalValue(numerator, denominator);
  148. }
  149. /// <summary>
  150. /// Gets or sets the Document's dots-per-unit scale in the X direction.
  151. /// </summary>
  152. /// <remarks>
  153. /// If DpuUnit is equal to MeasurementUnit.Pixel, then this property may not be set
  154. /// to any value other than 1.0. Setting DpuUnit to MeasurementUnit.Pixel will reset
  155. /// this property to 1.0. This property may only be set to a value greater than 0.
  156. /// One dot is always equal to one pixel. This property will not return a value less
  157. /// than MinimumDpu, nor a value larger than MaximumDpu.
  158. /// </remarks>
  159. public double DpuX
  160. {
  161. get
  162. {
  163. PropertyItem[] pis = this.Metadata.GetExifValues(ExifTagID.XResolution);
  164. if (pis.Length == 0)
  165. {
  166. double defaultDpu = GetDefaultDpu(this.DpuUnit);
  167. this.DpuX = defaultDpu;
  168. return defaultDpu;
  169. }
  170. else
  171. {
  172. try
  173. {
  174. uint numerator;
  175. uint denominator;
  176. Exif.DecodeRationalValue(pis[0], out numerator, out denominator);
  177. if (denominator == 0)
  178. {
  179. throw new DivideByZeroException(); // will be caught by the below catch{}
  180. }
  181. else
  182. {
  183. return Math.Min(MaximumDpu, Math.Max(MinimumDpu, (double)numerator / (double)denominator));
  184. }
  185. }
  186. catch
  187. {
  188. this.Metadata.RemoveExifValues(ExifTagID.XResolution);
  189. return this.DpuX; // recursive call;
  190. }
  191. }
  192. }
  193. set
  194. {
  195. if (value <= 0.0)
  196. {
  197. throw new ArgumentOutOfRangeException("value", value, "must be > 0.0");
  198. }
  199. if (this.DpuUnit == MeasurementUnit.Pixel && value != 1.0)
  200. {
  201. throw new ArgumentOutOfRangeException("value", value, "if DpuUnit == Pixel, then value must equal 1.0");
  202. }
  203. byte[] data = GetDoubleAsRationalExifData(value);
  204. PropertyItem pi = Exif.CreatePropertyItem(ExifTagID.XResolution, ExifTagType.Rational, data);
  205. this.Metadata.ReplaceExifValues(ExifTagID.XResolution, new PropertyItem[1] { pi });
  206. Dirty = true;
  207. }
  208. }
  209. /// <summary>
  210. /// Gets or sets the Document's dots-per-unit scale in the Y direction.
  211. /// </summary>
  212. /// <remarks>
  213. /// If DpuUnit is equal to MeasurementUnit.Pixel, then this property may not be set
  214. /// to any value other than 1.0. Setting DpuUnit to MeasurementUnit.Pixel will reset
  215. /// this property to 1.0. This property may only be set to a value greater than 0.
  216. /// One dot is always equal to one pixel. This property will not return a value less
  217. /// than MinimumDpu, nor a value larger than MaximumDpu.
  218. /// </remarks>
  219. public double DpuY
  220. {
  221. get
  222. {
  223. PropertyItem[] pis = this.Metadata.GetExifValues(ExifTagID.YResolution);
  224. if (pis.Length == 0)
  225. {
  226. // If there's no DpuY setting, default to the DpuX setting
  227. double dpu = this.DpuX;
  228. this.DpuY = dpu;
  229. return dpu;
  230. }
  231. else
  232. {
  233. try
  234. {
  235. uint numerator;
  236. uint denominator;
  237. Exif.DecodeRationalValue(pis[0], out numerator, out denominator);
  238. if (denominator == 0)
  239. {
  240. throw new DivideByZeroException(); // will be caught by the below catch{}
  241. }
  242. else
  243. {
  244. return Math.Min(MaximumDpu, Math.Max(MinimumDpu, (double)numerator / (double)denominator));
  245. }
  246. }
  247. catch
  248. {
  249. this.Metadata.RemoveExifValues(ExifTagID.YResolution);
  250. return this.DpuY; // recursive call;
  251. }
  252. }
  253. }
  254. set
  255. {
  256. if (value <= 0.0)
  257. {
  258. throw new ArgumentOutOfRangeException("value", value, "must be > 0.0");
  259. }
  260. if (this.DpuUnit == MeasurementUnit.Pixel && value != 1.0)
  261. {
  262. throw new ArgumentOutOfRangeException("value", value, "if DpuUnit == Pixel, then value must equal 1.0");
  263. }
  264. byte[] data = GetDoubleAsRationalExifData(value);
  265. PropertyItem pi = Exif.CreatePropertyItem(ExifTagID.YResolution, ExifTagType.Rational, data);
  266. this.Metadata.ReplaceExifValues(ExifTagID.YResolution, new PropertyItem[1] { pi });
  267. Dirty = true;
  268. }
  269. }
  270. /// <summary>
  271. /// 像素换算到物理长度
  272. /// </summary>
  273. /// <param name="pixel"></param>
  274. /// <param name="resultUnit"></param>
  275. /// <returns></returns>
  276. public double PixelToPhysicalY(double pixel, MeasurementUnit resultUnit)
  277. {
  278. double result;
  279. if (resultUnit == MeasurementUnit.Pixel)
  280. {
  281. result = pixel;
  282. }
  283. else
  284. {
  285. MeasurementUnit dpuUnit = this.DpuUnit;
  286. if (resultUnit == dpuUnit)
  287. {
  288. double defaultDpuY = GetDefaultDpu(dpuUnit);
  289. result = pixel / defaultDpuY;
  290. //result = pixel / this.DpuY;
  291. }
  292. else if (dpuUnit == MeasurementUnit.Pixel)
  293. {
  294. double defaultDpuY = GetDefaultDpu(dpuUnit);
  295. result = pixel / defaultDpuY;
  296. }
  297. else if (dpuUnit == MeasurementUnit.Inch && resultUnit == MeasurementUnit.Mil)
  298. {
  299. double defaultDpuY = GetDefaultDpu(MeasurementUnit.Mil);
  300. result = pixel / defaultDpuY; // pixel / (CmPerInch * this.DpuY);
  301. }
  302. else if (dpuUnit == MeasurementUnit.Inch && resultUnit == MeasurementUnit.Centimeter)
  303. {
  304. double defaultDpuY = GetDefaultDpu(MeasurementUnit.Centimeter);
  305. result = pixel / defaultDpuY; // pixel / (CmPerInch * this.DpuY);
  306. }
  307. else if (dpuUnit == MeasurementUnit.Inch && resultUnit == MeasurementUnit.Millimeter)
  308. {
  309. double defaultDpuY = GetDefaultDpu(MeasurementUnit.Millimeter);
  310. result = pixel / defaultDpuY;
  311. }
  312. else if (dpuUnit == MeasurementUnit.Inch && resultUnit == MeasurementUnit.Micron)
  313. {
  314. double defaultDpuY = GetDefaultDpu(MeasurementUnit.Micron);
  315. result = pixel / defaultDpuY;
  316. }
  317. else if (dpuUnit == MeasurementUnit.Inch && resultUnit == MeasurementUnit.Nano)
  318. {
  319. double defaultDpuY = GetDefaultDpu(MeasurementUnit.Nano);
  320. result = pixel / defaultDpuY;
  321. }
  322. else
  323. {
  324. result = pixel / this.DpuX;//(pixel * CmPerInch) / this.DpuY;
  325. }
  326. }
  327. return result;
  328. }
  329. [field: NonSerialized]
  330. public event EventHandler DirtyChanged;
  331. private void OnDirtyChanged()
  332. {
  333. if (DirtyChanged != null)
  334. {
  335. DirtyChanged(this, EventArgs.Empty);
  336. }
  337. }
  338. /// <summary>
  339. /// Keeps track of whether the document has changed at all since it was last opened
  340. /// or saved. This is something that is not reset to true by any method in the Document
  341. /// class, but is set to false anytime anything is changed.
  342. /// This way we can prompt the user to save a changed document when they go to quit.
  343. /// </summary>
  344. public bool Dirty
  345. {
  346. get
  347. {
  348. if (this.disposed)
  349. {
  350. throw new ObjectDisposedException("Document");
  351. }
  352. return this.dirty;
  353. }
  354. set
  355. {
  356. if (this.disposed)
  357. {
  358. throw new ObjectDisposedException("Document");
  359. }
  360. if (this.dirty != value)
  361. {
  362. this.dirty = value;
  363. OnDirtyChanged();
  364. }
  365. }
  366. }
  367. /// <summary>
  368. /// Width of the document, in pixels. All contained layers must be this wide as well.
  369. /// </summary>
  370. public int Width
  371. {
  372. get
  373. {
  374. return width;
  375. }
  376. }
  377. /// <summary>
  378. /// Height of the document, in pixels. All contained layers must be this tall as well.
  379. /// </summary>
  380. public int Height
  381. {
  382. get
  383. {
  384. return height;
  385. }
  386. }
  387. /// <summary>
  388. /// The size of the document, in pixels. This is a convenience property that wraps up
  389. /// the Width and Height properties in one Size structure.
  390. /// </summary>
  391. public Size Size
  392. {
  393. get
  394. {
  395. return new Size(Width, Height);
  396. }
  397. }
  398. public Rectangle Bounds
  399. {
  400. get
  401. {
  402. return new Rectangle(0, 0, Width, Height);
  403. }
  404. }
  405. public Metadata Metadata
  406. {
  407. get
  408. {
  409. if (metadata == null)
  410. {
  411. metadata = new Metadata(userMetaData);
  412. }
  413. return metadata;
  414. }
  415. }
  416. /// <summary>
  417. /// Constructs a blank document (zero layers) of the given width and height.
  418. /// </summary>
  419. /// <param name="width"></param>
  420. /// <param name="height"></param>
  421. public StitchDocument(int width, int height)
  422. {
  423. this.width = width;
  424. this.height = height;
  425. this.Dirty = true;
  426. this.updateRegion = new Vector<Rectangle>();
  427. userMetaData = new NameValueCollection();
  428. Invalidate();
  429. }
  430. /// <summary>
  431. /// Called after deserialization occurs so that certain things that are non-serializable
  432. /// can be set up.
  433. /// </summary>
  434. /// <param name="sender"></param>
  435. public void OnDeserialization(object sender)
  436. {
  437. this.updateRegion = new Vector<Rectangle>();
  438. this.updateRegion.Add(this.Bounds);
  439. Dirty = true;
  440. }
  441. [field: NonSerialized]
  442. public event InvalidateEventHandler Invalidated;
  443. /// <summary>
  444. /// Raises the Invalidated event.
  445. /// </summary>
  446. /// <param name="e"></param>
  447. private void OnInvalidated(InvalidateEventArgs e)
  448. {
  449. if (Invalidated != null)
  450. {
  451. Invalidated(this, e);
  452. }
  453. }
  454. /// <summary>
  455. /// Causes the whole document to be invalidated, forcing a full rerender on
  456. /// the next call to Update.
  457. /// </summary>
  458. public void Invalidate()
  459. {
  460. Dirty = true;
  461. Rectangle rect = new Rectangle(0, 0, Width, Height);
  462. updateRegion.Clear();
  463. updateRegion.Add(rect);
  464. OnInvalidated(new InvalidateEventArgs(rect));
  465. }
  466. public unsafe static StitchDocument FromMat(OpenCvSharp.Mat mat)
  467. {
  468. if (mat == null) throw new ArgumentNullException("image"); //Console.WriteLine("size:" + new ColorBgra()); //Console.WriteLine("size2:" + sizeof(ColorBgrB));
  469. StitchDocument document = new StitchDocument(mat.Width, mat.Height);
  470. if (mat.Channels() == 4)
  471. {
  472. OpenCvSharp.Cv2.CvtColor(mat, mat, OpenCvSharp.ColorConversionCodes.BGRA2BGR);
  473. }
  474. StitchSurface surface = new StitchSurface(new Size(mat.Width, mat.Height), mat.Channels(), mat); //surface.Clear(ColorBgrB.FromColor(Color.Red));
  475. surface.PixelFormat = mat.Channels() == 3 ? PixelFormat.Format24bppRgb : PixelFormat.Format32bppArgb;
  476. surface.scan0.VoidStar = (void*)mat.Data;
  477. surface.Stride = (int)mat.Step();
  478. document.surface = surface;
  479. document.Invalidate();
  480. return document;
  481. }
  482. ~StitchDocument()
  483. {
  484. Dispose(false);
  485. }
  486. public void Dispose()
  487. {
  488. Dispose(true);
  489. GC.SuppressFinalize(this);
  490. }
  491. private bool disposed = false;
  492. private void Dispose(bool disposing)
  493. {
  494. if (!disposed) disposed = true;
  495. }
  496. }
  497. }