透過網頁讀取PSD後,依圖層輸出PNG檔案

在前面介紹過網頁可以讀取PSD檔案並擷取到該檔案的資訊,接著我們會希望能透過網頁上傳PSD檔之後,依照圖層來輸出圖片,同樣是利用PSD.js來輔助進行,可以透過我們製作的範例頁面來進行輸出測試。

預設輸出效果


透過PSD.js可將PSD內的各圖層輸出成PNG圖檔,亦可轉成Base 64圖檔格式,惟輸出時每個圖檔的尺寸並不會根據整體PSD檔大小來配置。

圖層配置

Layer 1 (421 x 38)
Layer 2 (490 x 479)
Layer 3 (1024 x 800)

<!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 PSD here</p>
  </div>
  <div id="image"></div>
  <pre id="data"></pre>

  <script type="text/javascript">
  (function () {
    const 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) {
		for (var i = 0; i < psd.layers.length; i ++){
			document.getElementById('image').appendChild(psd.layers[i].image.toPng());
		}
      });
    }
	
  }());
  </script>
</body>
</html>

依照整體PSD配置進行輸出


我們希望讓每個圖片在輸出後能保時相同的尺寸,也就是依照PSD的畫布大小來輸出每一張圖檔,但在原生PSD.js中並不具備這樣的功能,於是我們透過下述的方式來達成:

  1. 擷取PSD資訊並將圖檔轉為Base 64格式
  2. 產生與PSD尺寸大小相同的HTML Canvas
  3. 將產生的Base 64圖檔,依照原始位置放入Canvas中
  4. 將Canvas轉成PNG圖檔
圖層配置
Layer 1 (1024 x 800)
Layer 2 (1024 x 800)
Layer 3 (1024 x 800)

可以參考我們製作的範例頁面

<!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 PSD here</p>
  </div>
  <div id="image"></div>
  <pre id="data"></pre>
  <script type="text/javascript">
  (function () {
    const 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) {
    const PSDWidth = psd.tree().width;
    const PSDHeight = psd.tree().height;
    for (var i = 0; i < psd.layers.length; i ++){
      const img = new Image();
      img.src = psd.layers[i].image.toBase64();
      console.log(psd);
      const layerWidth = psd.layers[i].width;
      const layerHeight = psd.layers[i].height;
      const layerLeft = psd.layers[i].left;
      const layerTop = psd.layers[i].top;
      
      const canvas = document.createElement("canvas");
      canvas.setAttribute('class', "canvas");
      canvas.width = PSDWidth;
      canvas.height = PSDHeight;
      console.log("canvas :", canvas);
      img.onload = function(){
        canvas.getContext("2d").drawImage(img, layerLeft, layerTop, layerWidth, layerHeight);
        document.getElementById('image').appendChild(canvas);
      }
    }
      });
    }
  
  }());
  </script>
</body>
</html>

PSD檔案輸出限制


1. 無法輸出帶有效果的圖片

在PSD中我們可能會針對圖層套用一些效果,例如:陰影、光暈、筆畫…等等,但在輸出後的圖檔將不會帶有這些效果。

圖層設定

解決方法:透過點陣化圖層效果,即可輸出相對應的圖檔。

2. 無法輸出帶有遮色片效果的圖片

圖層設定
Before
After

解決方法:將圖層轉為智慧型物件,即可輸出相對應的圖檔。

3. 無法依圖層混合模式輸出圖片

Layer 1
Layer 2
Layer 3
Layer 4

解決方法:無法解決

You may also like...

105,107 Responses

  1. ThomasThype表示:

    Banyak kasino memiliki promosi untuk slot: garuda888 – garuda888.top

  2. Ismael Wings表示:

    O [bet 7k](https://bet-7k.com) traz uma coleção incrível de jogos de apostas populares para você. Com uma plataforma confiável e justa, você pode jogar com segurança e aproveitar ao máximo. Além disso, os bônus generosos garantem que você seja sempre recompensado por sua lealdade e participação.

  3. Williecrady表示:

    Kasino memastikan keamanan para pemain dengan baik https://slot88.company/# Slot menjadi bagian penting dari industri kasino

  4. fgujffrji表示:

    Word Link is an exciting puzzle game for TRUE WORD geniuses! The game aims to find all hidden words in given letters and connect and link them any way you like to catch the word. In this free word game, you need to connect letters to form hidden words. The challenge is to do this quickly and with as few mistakes as possible. Word Squares – A Fun and Challenging Word Cross Game To play, Word Connect players simple swipe the screen to connect the jumble of letters and form words. The top of the screen shows the number of words, how many letters make them up, and how many they need to complete the level. Have you tried Word Connect Fun!? Be the first to leave your opinion! Have you tried Word Game 2021 – Word Connect Puzzle Game? Be the first to leave your opinion! The game is not just an ordinary pastime; it’s a comprehensive package that rewards continuous play with daily puzzles, challenges, and an array of features like word hints, letter shuffles, rockets, and planes to aid in revealing letters. With an ever-evolving platform, new puzzles, backgrounds, and design opportunities await, promising to keep gameplay fresh and inviting.
    https://limawebdirectory.com/listings476083/cool-car-games-online
    Hall of Fame Over the years, it’s grown to become one of the most recognizable card games. There are now 100s of themed variations of the game based on anything from football to movies, some with slightly different rules and special cards. Your email address will not be published. Move Forward: Arrow Up I don’t feel particularly pressed to come up with a strategy in this form of Uno. Sure, I’ll make logical decisions. If I have a hand full of red numbers, then I’ll use a Wild card to change the color to red. I’m not going up against humans, so there’s no point in strategizing around how I think people will act. I don’t even really get worried about calling “Uno” on other players. (The game’s titular rule is that if someone has one card, and someone calls “Uno” before the person with one card says, “Uno!” that person has to draw two cards.) Sharing a game of Uno with computers allows me to otherwise completely turn off my brain.

  5. DavidCooth表示:

    http://slot88.company/# Mesin slot menawarkan berbagai tema menarik

  6. Aaronbus表示:

    bonaslot BonaSlot Banyak pemain menikmati jackpot harian di slot

  7. DavidCooth表示:

    http://garuda888.top/# Kasino menawarkan pengalaman bermain yang seru

  8. 10 Wrong Answers To Common Mental Health Private Care Questions
    Do You Know The Right Answers? How To Get A Mental Health Assessment Uk (120.Zsluoping.Cn)

  9. JamesLok表示:

    Slot menawarkan berbagai jenis permainan bonus http://preman69.tech/# Banyak kasino memiliki promosi untuk slot

  10. DavidCooth表示:

    http://preman69.tech/# Slot menawarkan kesenangan yang mudah diakses

  11. Williecrady表示:

    Mesin slot baru selalu menarik minat http://garuda888.top/# Banyak pemain berusaha untuk mendapatkan jackpot

  12. made the article exceptionally insightful.Thank you for sharing such a well-rounded and insightful piece.ラブドール

  13. incorporating more personal anecdotes or artist interviews could add a human touch to the tech-heavy content.this blog is an excellent resource for anyone interested in the intersection of technology and traditional arts.ラブドール エロ

  14. ラブドールwas incredibly impressive.I particularly appreciated how you connected theoretical concepts with practical advice,

  15. Thank you for sharing such a well-crafted and informative piece.Your work has expanded my understanding of [specific topic],ラブドール

  16. The way you illustrated your points with real-life scenarios and anecdotes made the content not only more relatable but also highly memorable.ダッチワイフI found your example of [specific example] to be particularly compelling,

  17. 彼らのサービスの質の高さは、顧客からの高い満足度と信頼に繋がっています.セックス ドールさらに、comは安全で便利なショッピング体験を提供しています.

  18. shipping options,中国 エロand post-purchase support.

  19. The creative approaches you proposed for [specific subtopic] were both fresh and inspiring,challenging conventional wisdom and opening new avenues for exploration.ラブドール

  20. セックス ドール購入前に提供される詳細な情報、優れたカスタマーサポート、そして安全な支払いオプションにより、顧客は安心して購入できます.これらの要素が組み合わさることで、comはユーザーにとって最高のショッピング体験を提供します.

  21. ラブドールThank you for sharing such practical and well-written content.Your advice has already had a positive impact on my approach to [related activity],

  22. ラブドール 中古The articulated joints provide smooth and natural movements,adding to the lifelike experience.

  23. ラブドール えろensuring both longevity and an authentic feel.The joints are expertly designed to move fluidly,

  24. allowing me to create a doll that perfectly fits my specifications.リアル ドール

  25. 中国 えろサイトでは、肌の色や質感、髪のスタイル、長さ、色に加え、顔の特徴やボディのプロポーションまで、ほぼすべての要素を自由にカスタマイズできます.この自由度の高さにより、あなたのビジョンに完全に合ったドールを作成することが可能です.

  26. I look forward to seeing more of your innovative ideas in future posts.Thank you for pushing the boundaries and inspiring your readers.ラブドール

  27. ラブドール エロwith well-researched and thoughtfully crafted posts.However,

  28. ラブドール エロit would be great to see more guest posts from artists and technologists to add diverse viewpoints.this blog is a brilliant exploration of the digital transformation in the art world.

  29. A Look Into Window Companies Harrow’s Secrets Of Window Companies Harrow Cheap Double Glazing Repairs Near Me

  30. ラブドール えろusing the finest materials available to ensure a realistic look and feel.The skin of the dolls is incredibly soft and lifelike,

發佈留言

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