PSDText.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using System.Xml;
  6. using System.Xml.Serialization;
  7. namespace PSDText
  8. {
  9. public class PSDText
  10. {
  11. private readonly string _xmlData;
  12. private readonly XmlNamespaceManager _ns = new XmlNamespaceManager(new NameTable());
  13. public List<TextData> TextData;
  14. private string Readxmpmeta(string path)
  15. {
  16. var sb = new StringBuilder(1000);
  17. using (var sr = new StreamReader(path))
  18. {
  19. sr.ReadLine(); //skip first line
  20. var line = sr.ReadLine();
  21. if (string.IsNullOrWhiteSpace(line))
  22. return string.Empty;
  23. var read = line.StartsWith("<x:xmpmeta");
  24. while (read)
  25. {
  26. if (line.StartsWith("</x:xmpmeta>"))
  27. read = false;
  28. sb.Append(line);
  29. line = sr.ReadLine();
  30. if (string.IsNullOrWhiteSpace(line))
  31. return sb.ToString();
  32. }
  33. }
  34. return sb.ToString();
  35. }
  36. private void AddXMLNamespaces()
  37. {
  38. _ns.AddNamespace("x", "adobe:ns:meta/");
  39. _ns.AddNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
  40. _ns.AddNamespace("photoshop", "http://ns.adobe.com/photoshop/1.0/");
  41. }
  42. private XmlDocument ReadXML()
  43. {
  44. var xml = new XmlDocument();
  45. using (var sr = new StringReader(_xmlData))
  46. using (var reader = XmlReader.Create(sr))
  47. {
  48. xml.Load(reader);
  49. }
  50. return xml;
  51. }
  52. public List<TextData> GetTextData()
  53. {
  54. var xml = ReadXML();
  55. var data = new List<TextData>();
  56. var textNodes =
  57. xml.SelectNodes("/x:xmpmeta/rdf:RDF/rdf:Description/photoshop:TextLayers/rdf:Bag/rdf:li", _ns);
  58. foreach (XmlNode textNode in textNodes)
  59. {
  60. var name = textNode.SelectSingleNode("./photoshop:LayerName", _ns)?.InnerText;
  61. var text = textNode.SelectSingleNode("./photoshop:LayerText", _ns)?.InnerText;
  62. data.Add(new TextData{Name = name, Text = text});
  63. }
  64. return data;
  65. }
  66. public PSDText(string path)
  67. {
  68. if (!File.Exists(path))
  69. throw new Exception($"File {path} doesn't exist!");
  70. _xmlData = Readxmpmeta(path);
  71. AddXMLNamespaces();
  72. TextData = GetTextData();
  73. }
  74. public void SaveAsXML(string path)
  75. {
  76. var serializer = new XmlSerializer(typeof(List<TextData>));
  77. using (var sr = new StreamWriter(path))
  78. {
  79. serializer.Serialize(sr, TextData);
  80. }
  81. }
  82. }
  83. }