透過網頁讀取Photoshop PSD檔案內容

在專案中有需要透過網頁來讀取Photoshop PSD檔案的內部資訊,我們透過PSD.js備用載點)來實現這樣的功能,在官方提供的功能展示頁中,我們可以看到在頁面中只需引入psd.min.js後,加入透過少量的Javascript就可以針對PSD進行解析。

<!DOCTYPE html>
<html>
<head>
  <title>psd.js image example</title>
  <style type="text/css">
  body, html {
    padding: 0;
    margin: 0;
  }
  #dropzone {
    width: 500px;
    height: 100px;
    border: 1px #ababab dashed;
    margin: 50px auto;
  }
  #dropzone p {
    text-align: center;
    line-height: 100px;
    margin: 0;
    padding: 0;
  }
  #image {
    text-align: center;
  }
  </style>
  <script type="text/javascript" src="psd.min.js"></script>
</head>
<body>
  <div id="dropzone">
    <p>Drop here</p>
  </div>
  <div id="image"></div>
  <pre id="data"></pre>
  <script type="text/javascript">
  (function () {
    var PSD = require('psd');
    document.getElementById('dropzone').addEventListener('dragover', onDragOver, true);
    document.getElementById('dropzone').addEventListener('drop', onDrop, true);
    function onDragOver(e) {
      e.stopPropagation();
      e.preventDefault();
      e.dataTransfer.dropEffect = 'copy';
    }
    function onDrop(e) {
      e.stopPropagation();
      e.preventDefault();
      PSD.fromEvent(e).then(function (psd) {
        var data = JSON.stringify(psd.tree().export(), undefined, 2);
        document.getElementById('data').innerHTML = data;
        document.getElementById('image').appendChild(psd.image.toPng());
      });
    }
  }());
  </script>
</body>
</html>

我們透過下圖這樣的一個PSD檔案對頁面進行測試,檔案中共有三個圖層,包含一個文字圖層。

頁面將PSD分析出結果後,以json格式顯示在頁面上,可以看到文字圖層的部分,不僅能讀到圖層名稱也包含文字內容和字型名稱。

{
  "children": [
    {
      "type": "layer",
      "visible": true,
      "opacity": 1,
      "blendingMode": "normal",
      "name": "Photoshop Text",
      "left": 302,
      "right": 723,
      "top": 90,
      "bottom": 128,
      "height": 38,
      "width": 421,
      "mask": {},
      "text": {
        "value": "THIS IS TEXT LAYER",
        "font": {
          "name": "MyriadPro-Regular\u0000",
          "sizes": [
            53
          ],
          "colors": [
            [
              0,
              0,
              0,
              255
            ]
          ],
          "alignment": [
            "center"
          ]
        },
        "left": 0,
        "top": 0,
        "right": 0,
        "bottom": 0,
        "transform": {
          "xx": 1,
          "xy": 0,
          "yx": 0,
          "yy": 1,
          "tx": 513,
          "ty": 127
        }
      },
      "image": {}
    },
    {
      "type": "layer",
      "visible": true,
      "opacity": 1,
      "blendingMode": "normal",
      "name": "PSD Icon",
      "left": 287,
      "right": 738,
      "top": 209,
      "bottom": 669,
      "height": 460,
      "width": 451,
      "mask": {},
      "image": {}
    },
    {
      "type": "layer",
      "visible": true,
      "opacity": 1,
      "blendingMode": "normal",
      "name": "Background",
      "left": 0,
      "right": 1024,
      "top": 0,
      "bottom": 800,
      "height": 800,
      "width": 1024,
      "mask": {},
      "image": {}
    }
  ],
  "document": {
    "width": 1024,
    "height": 800,
    "resources": {
      "layerComps": [],
      "guides": [],
      "slices": []
    }
  }
}

You may also like...

21,495 Responses

  1. Всем рекомендую! На этом сайте Вы можете приобрестигвозди toua

  2. Всем рекомендую! На этом сайте Вы можете приобрестигвозди для монтажного пистолета

  3. Всем рекомендую!Top Architects of Kazakhstan Наша команда архитекторов, инженеров, специалистов по ландшафту, дизайнеров работает в полном соответствии с требованиями мировой практики архитектуры и строительства, чтобы обеспечить наилучшую эффективность апробированных нами и протестированных временем решений. При этом мы всегда в поисках инновационных вариантов развития своей проектной деятельности, а постоянный обмен идеями и диалог внутри команды способствует сокращению сроков принятия решений, быстрого реагирования на изменения и требуемые корректировки.

  4. Всем рекомендую!лучшие архитекторы казахстана Наша команда архитекторов, инженеров, специалистов по ландшафту, дизайнеров работает в полном соответствии с требованиями мировой практики архитектуры и строительства, чтобы обеспечить наилучшую эффективность апробированных нами и протестированных временем решений. При этом мы всегда в поисках инновационных вариантов развития своей проектной деятельности, а постоянный обмен идеями и диалог внутри команды способствует сокращению сроков принятия решений, быстрого реагирования на изменения и требуемые корректировки.

  5. Всем рекомендую!архитектурная компания Наша команда архитекторов, инженеров, специалистов по ландшафту, дизайнеров работает в полном соответствии с требованиями мировой практики архитектуры и строительства, чтобы обеспечить наилучшую эффективность апробированных нами и протестированных временем решений. При этом мы всегда в поисках инновационных вариантов развития своей проектной деятельности, а постоянный обмен идеями и диалог внутри команды способствует сокращению сроков принятия решений, быстрого реагирования на изменения и требуемые корректировки.

  6. Всем рекомендую!Aviator играть

  7. Всем рекомендую!Aviator играть

  8. Всем рекомендую!Aviator играть

  9. Всем рекомендую!игра Авиатор

  10. sitemap表示:

    Fantastic goods from you, man. I havve understgand your stuff previous too aand you’re just extremely
    wonderful. I really lioe whuat you have acquired here, cerainly like what you’re stating aand
    the wayy iin which yyou ssay it. Youu makie itt enjoyable andd
    you still caree foor tto keep it smart. I can’twait too read farr moore fro
    you. This iss reaally a great website.

  11. sitemap表示:

    Good day! Thiss post coould noot bee written anyy better! Reading through ths post reminds mme oof myy good old room mate!
    He always kpt chating abou this. I will forward tis write-up to him.
    Prety sre hee wipl have a goopd read. Thank for sharing!

  12. sitemap表示:

    No matter if som one searchhes ffor hiss vjtal thing, soo he/she wishes to be available
    thatt iin detail, sso thwt tging iis maintained over here.

  13. sitemap表示:

    These are inn fac fantyastic ideas inn about blogging.

    You have touche spme pleasant things here.Any way keep up wrinting.

  14. sitemap.xml表示:

    Thiss piece of writing wikl assist the internet visitors for setting
    up neew website oor even a blog frm start tto end.

  15. sitemap.xml表示:

    Hi there, i red yoiur blog fom timee tto time and i
    owwn a ssimilar one aand i was just curious if yoou get
    a lott of soam comments? If sso howw do you prevednt it, any plugin oor anything yoou cann recommend?
    I gget soo mich lately it’s driviing me insane sso any assistance iis vvery much appreciated.

  16. sitemap表示:

    Linnk exchange is nothibg else except iit is just
    placing the otherr person’s weeb sire lonk oon you age att prlper pace aand other person ill apso doo same iin suupport of you.

  17. sitemap表示:

    Hello, every time i used to check webpage posts here in the early hours in the dawn, as i enjoy to learn mofe
    and more.

  18. sitemap表示:

    Hi there! This artiicle could noot bbe writgten any better!
    Looiing thrlugh thus post reminds mme of myy previous roommate!

    He continually kept preaching about this. I’ll sernd this article
    too him. Faurly ccertain he’s goin tto hqve a good read.
    Maany thanks forr sharing!

  19. xnxx movies表示:

    Gredat blog right here! Also our website lots up very fast!
    Whaat web hosdt aare youu the usawge of? Can I am getting yor affiliate
    hypetlink to your host? I desiree my wweb siite loded
    up as fast as yours lol

  20. Здесь можно не дорого и качественно оформить Справка 095 у

  21. Всем рекомендую!lucky jet 1win

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。