透過網頁讀取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...

61,762 Responses

  1. It is perfect time to make a few plans for the long run and
    it is time to be happy. I have read this submit and if I may I want to recommend you few interesting things or suggestions.
    Perhaps you could write subsequent articles referring to this article.
    I desire to read more issues about it!

  2. 11 Creative Ways To Write About Space Saving Treadmill With Incline What Is 10 Incline On Treadmill

  3. HaroldBig表示:

    rybelsus cost: rybelsus price – buy semaglutide online

  4. Jeremypag表示:

    ozempic generic buy ozempic ozempic

  5. Профессиональный сервисный центр по ремонту сигвеев в Москве.
    Мы предлагаем: сигвей ремонт аккумулятора
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  6. Профессиональный сервисный центр по ремонту сетевых хранилищ в Москве.
    Мы предлагаем: сервис по ремонту сетевых хранилищ
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  7. HaroldBig表示:

    buy ozempic pills online: ozempic generic – ozempic coupon

  8. JacobGed表示:

    online sportsbook bonuses: Promotional offers from betting sites that provide free bets to users, allowing them to place wagers without financial risk.

  9. Filomena表示:

    It’s hard to come by experienced people in this particular topic, however, you sound like you know what you’re talking about!
    Thanks

  10. RamonRek表示:

    semaglutide tablets: buy rybelsus online – cheapest rybelsus pills

  11. BarryDof表示:

    http://ozempic.art/# ozempic online

  12. Captivating and illuminating examination of the issue. Your analysis was thorough and well-supported, providing readers with
    a thorough knowledge of the key topics at possession.

    I would be ecstatic to discuss supplementary on this content.
    If you are amenable, I would kindly invite you to participate in us on the SBOBET ecosystem,
    where we would continue our dialogue in a even more
    interactive domain.

    My page :: sbobet singapore

  13. BarryDof表示:

    http://ozempic.art/# Ozempic without insurance

  14. Jeremypag表示:

    semaglutide tablets semaglutide tablets rybelsus cost

  15. Pvc Window Hinges: What No One Is Talking About Upvc Window hinge

  16. How To Tell The Good And Bad About Realistic Sexdoll sex doll Realistic

  17. Профессиональный сервисный центр по ремонту объективов в Москве.
    Мы предлагаем: замена объектива фотоаппарата
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  18. Сервисный центр предлагает починка телевизоров avel качественый ремонт телевизора avel

  19. AaronIdelt表示:

    7 simple secrets to eating the Mediterranean way
    Площадка кракен
    What if “diet” wasn’t a dirty word?

    During Suzy Karadsheh’s childhood in Port Said, Egypt, diet culture was nonexistent.

    “My parents emphasized joy at the table, rather than anything else,” Karadsheh said. “I grew up with Mediterranean lifestyle principles that celebrate eating with the seasons, eating mostly whole foods and above all else, sharing.”

    But when Karadsheh moved to the United States at age 16, she witnessed people doing detoxes or restricting certain food groups or ingredients. Surrounded by that narrative and an abundance of new foods in her college dining hall, she says she “gained the freshman 31 instead of the freshman 15.” When she returned home to Egypt that summer, “I eased back into eating the Mediterranean food that I grew up with. During the span of about two months, I shed all of that weight without thinking I was ever on a diet.”
    To help invite joy back to the table for others — and to keep her family’s culinary heritage alive for her two daughters (now 14 and 22) — Atlanta-based Karadsheh launched The Mediterranean Dish food blog 10 years ago. Quickly, her table started getting filled with more than just her friends and family.

    “I started receiving emails from folks whose doctors had prescribed the Mediterranean diet and were seeking approachable recipes,” Karadsheh said. The plant-based eating lifestyle, often rated the world’s best diet, can reduce the risk for diabetes, high cholesterol, dementia, memory loss and depression, according to research. What’s more, the meal plan has been linked to stronger bones, a healthier heart and longer life.

    Preparing meals the Mediterranean way, according to Karadsheh, can help you “eat well and live joyfully. To us, ‘diet’ doesn’t mean a list of ‘eat this’ and ‘don’t eat that.’” Instead of omission, Karadsheh focuses on abundance, asking herself, “what can I add to my life through this way of living? More whole foods, vegetables, grains, legumes? Naturally, when you add these good-for-you ingredients, you eat less of what’s not as health-promoting,” she told CNN.

  20. Toto macau表示:

    7 Simple Secrets To Completely Intoxicating Your Link Togel Toto macau

  21. Evyjrz表示:

    buy betnovate online – adapalene where to buy buy monobenzone online

  22. Frankevild表示:

    http://rybelsus.shop/# semaglutide tablets

  23. HaroldBig表示:

    semaglutide cost: rybelsus coupon – cheapest rybelsus pills

  24. Your style is unique in comparison to other folks I have read stuff from.
    I appreciate you for posting when you have the opportunity, Guess I will just book mark this web site.

  25. Amparo表示:

    How To Find The Perfect Bioethanol Fire Pit On The Internet bio flame fireplace (Amparo)

  26. HaroldBig表示:

    semaglutide cost: semaglutide cost – buy semaglutide pills

發佈留言

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