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

108,749 Responses

  1. What’s The Good And Bad About Where To Get Pallets wooden palette​ (mozillabd.science)

  2. Charleskepsy表示:

    pharmacy coupons https://xxlmexicanpharm.com/# mexican pharmaceuticals online

  3. 20ft Tunnel Container 101 This Is The Ultimate Guide For Beginners Tunnel Solutions

  4. WillieRap表示:

    MegaIndiaPharm: MegaIndiaPharm – MegaIndiaPharm

  5. Henry表示:

    9 Signs That You’re The Buy A1 And A2 Driving License Online Expert Köpa A1 och
    A2 Körkort Online; Henry,

  6. Buy Arvin Biewer Yorkshire Terrier Mini: The Ugly Truth About Buy Arvin Biewer Yorkshire Terrier Mini Marta Mini Yorkshire Terrier Kaufen

  7. Charleskepsy表示:

    prescription free canadian pharmacy https://discountdrugmart.pro/# discount drugs

  8. Davidmoits表示:

    purple pharmacy mexico price list: buying prescription drugs in mexico online – xxl mexican pharm

  9. The 10 Scariest Things About Paisley Hyacinth Macaw For Sale Paisley Hyacinth
    Macaw For Sale (http://Www.Lqqm.Com/)

  10. Regan Janoff表示:

    A [bet ano](https://betanocasino-88.com) prioriza seus usuários com atendimento ao cliente disponível a qualquer hora, todos os dias da semana. A equipe especializada resolve suas dúvidas de forma rápida e eficiente, garantindo que sua experiência na plataforma seja sempre positiva e sem complicações.

  11. 5 Buy Driving License Online Projects For Every Budget Kup Prawo jazdy kat a

  12. Tunnel Container Uses Tools To Ease Your Everyday Lifethe Only Tunnel Container Uses Trick That Every Person Must Learn Tunnel Container uses

  13. Davidmoits表示:

    xxl mexican pharm: xxl mexican pharm – xxl mexican pharm

  14. Porterfax表示:

    MegaIndiaPharm indian pharmacy MegaIndiaPharm

  15. Guide To 20ft Shipping Container For Sale UK In 2024 Guide
    To 20ft Shipping Container For Sale UK In 2024 20Ft Shipping Containers

  16. Large pallets表示:

    Why Nobody Cares About Pallet Prices Large pallets

  17. WillieRap表示:

    Online medicine order: top 10 online pharmacy in india – indian pharmacy

  18. Круглосуточная поставка спиртного в Москве: комфорт или проблема?

    Как это работает?

    24-часовая поставка алкоголя в Москве осуществляется посредством многообразные службы:

    Интернет-сервисы: Профильные сайты и приложения, которые дают широкий выбор спиртных продуктов с поставкой на дом. Заведения общепита и бары: Отдельные заведения, имеющие разрешение на продажу спиртного, предлагают поставку своей продукции в вечернее время. Доставщики службы: Компании, что взаимодействуют с лицензированными продавцами спиртного и проводят поставку по запросу. Плюсы:

    Комфорт: Шанс приобрести любимый напиток, не покидая из дома, в любое время суток. доставка алкоголя в москве – Сбережение часа: Не требуется терять время на поход в магазин, особо в вечернее время. Широкий выбор: Обширный ассортимент спиртных продуктов, в том числе редкие и особенные позиции. Возможность для вечеринок и событий: Быстрая поставка дает возможность быстро пополнить резервы алкоголя, если это необходимо. Недостатки и споры:

    Законность: В России не разрешена продажа алкоголя в вечернее время (с 23:00 до 8:00). Сервисы доставки, что предлагают круглосуточную доставку, обычно используют различные схемы, которые могут быть противозаконными. Употребление спиртного: Легкий доступ к спиртному в любое время способен способствовать росту употребления, что может иметь отрицательные результаты для здоровья. Контроль над реализацией несовершеннолетним: Имеется риск, что курьеры способны не контролировать лета клиентов, что способен вызвать к реализации алкоголя несовершеннолетним.

  19. What NOT To Do Within The Buy German Shepherd Puppies Industry purebred german Shepherd puppy

  20. Www.metooo.io表示:

    Five Buy A1 And A2 Driving License Online Lessons From The Pros Buy A1
    And A2 Driving License Online A1 Driving Licence Is A
    Kind Of Licence For Drivers. It Enables Drivers To Operate Small Motorbikes With Cylinder Volume And Power Not Exceeding 11 KW.
    This Licence Can Be Obtained From The Age Of 16. It Is Possible To Update To An Unrestricted Category A Motorcycle License After Two
    Years. To Do So, The Driver Must Pass CBT, Theory Tests,
    And A Dry Run. CBT You Can Take A CBT (computer-based Testing) Course Online Or At
    An Authorized Training School. This Training Consists Of Practical And Theory
    Lessons. It Likewise Covers Road Safety And Using A Bike.
    It Is Very Important To Pass The Test In Order To Obtain An A1 Or A2 Licence.
    You Must Likewise Pass A First-aid Course And Have Your Eyes Taken A Look At.
    The Eye Test Costs About EUR7, And Can Be Conducted At Any Optician Or Ophthalmologist.

    Some First-aid Courses Supply Complimentary Eye Tests.
    Upon Passing The CBT, You Will Receive An A1 Licence, Which Permits You To Ride Motorbikes And Scooters With A Cylinder Volume Of
    As Much As 125 Cubic Centimeters. In Addition, You Can Ride Motor Trikes And Trial E-scooters With An Engine Power Of Approximately 15 KW.
    You Can Update To An A2 Licence After 2 Years, But You
    Should Take A Practical Exam. The A1 And
    A2 Licences Are Based Upon The Detailed System, Which Is Meant To Provide Youths The Chance To Acquire A Little Motorbike Licence (A1) Early
    And After That Slowly Increase The Efficiency Of Their Maker According To Their Riding
    Experience. After 2 Years, They Can Change To An A2 Licence, And After Another 2 Years, They Can Make The
    Jump To A Complete A-licence. In Order To Get An A2 Driving License,
    You Must Complete A Practical Exam And Pass A Theory Test Furthermore, You Should Be At Least 18 Years Old And Have A Legitimate Driving License Or Student License.
    You Will Also Need To Have A Helmet And Clothing That Fulfills The Nationwide Security Standards.
    Once You Pass The Theory And Practical Exams, You Will Be Issued A
    Driving Licence That Is Legitimate For 15 Years.
    It Is A Single, Plastic-coated Paper That Is Tough To Counterfeit.
    You Can Also Buy A Driving Licence A A1 A2 Online, However It’s Suggested
    That You Go To A Main Driving School And
    Take Your Tests With A Certified Instructor. In This Manner, You’ll Have More
    Self-confidence In Your Skills And Knowledge Of The Roadway.

    Theory Test The Theory Test Part Of The A1 And
    A2 Driving Licence Includes A Computer-based Exam, Consisting Of
    70 Concerns. Five Of These Are Sample Questions And Do Not
    Count Towards The Overall Score. The Test
    Takes 50 Minutes To Complete. You Should Address 52 Questions Properly To Pass The
    Test. It Is Recommended That You Utilize The Official Modification Products To Get Ready For Your Theory Test.

    You Can Buy These Online Or From NDLS Centres And Some Public
    Libraries. You Can Also Utilize The Free Online Practice
    Service Called Theory Test Pro. The Test Is Scored Automatically And Results Are Available Right Away.
    If You Are Not Happy With The Outcome, You Can Appeal The Decision. You Ought To Prevent Bring A Traveler During Your Theory Test.
    It Can Sidetrack You And Might Impact Your Performance. You Ought To Also Turn Off Any Device That Can Tape-record Audio Or
    Video Throughout The Test. In Addition, You Need
    To Wear A Helmet And Eye Security While Driving. Once You’ve Passed The Theory
    Test, You Can Begin Preparing For Your Useful Test. If You’re Obtaining A
    Brand-new Driver’s Licence, You’ll Need To Send An Application And
    A Driving Record. You Can Get An Application From NDLS
    Or A Driving School. If You Have A Category A1 Driving Licence, You Can Drive Motorbikes Up To
    35 KW. Nevertheless, You Should Pass A Useful Test Before You Can Upgrade To
    The Category A2 Driving Licence. There Is A Choice On The Driving Test Application For Individuals With Specials Needs To
    Indicate That They Need Assistance From An Interpreter
    Or A Sign Language Translator. If You’re A Handicapped
    Individual, You Can Ask For A Special Plan By Calling
    0818 606 106. If You Have A Category A1 Driving License And
    Desire To Update To The A2 Driving Licence, You Must Take A Practical
    Assessment After Two Years. If You Desire To Avoid This Step, You Can Register In An A1->> A2 Or A2->> A Elevation Course.
    köpa Körkort Online (http://Www.metooo.io)

  21. Woodrow表示:

    10 Websites To Help You Develop Your Knowledge About Pallet Wood For Sale where to
    get pallets​ (Woodrow)

  22. 15 Terms Everyone Who Works In Buy A Driving License Industry Should Know
    Kup Prawo Jazdy Kat A Online​

  23. Buy Driving License Online: 11 Things That You’re Failing To Do Köpa A2 Körkort

  24. Nine Things That Your Parent Teach You About Blondie Scarlet Macaw Bird Blondie scarlet macaw bird

  25. You’ll Never Guess This Containers For Sale Middlesbrough’s Tricks containers for Sale middlesbrough

  26. You’ll Never Guess This Conversions Containers’s Secrets Conversions Containers (vuf.minagricultura.gov.co)

  27. WillieRap表示:

    drugmart: discount drug mart – discount drugs

  28. WillieRap表示:

    medication from mexico pharmacy: xxl mexican pharm – xxl mexican pharm

發佈留言

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