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

38,981 Responses

  1. ラブドール セックスby taking research findings related to psychopathy at any workplace and branding them “corporate psychopathy”.This is not unlike prefacing “narcissism” with “artistic” since,

  2. Отличный сайт! Всем рекомендую!бумажные пакеты

  3. Hi there, after reading this amazing paragraph i am too glad to share my experience here with colleagues.

  4. sumclub表示:

    Its like you read my mind! You seem to know so much about
    this, like you wrote the book in it or something. I think that you could do with some pics to drive the message home a bit, but other than that, this is excellent blog.
    A fantastic read. I will definitely be back.

  5. Henrylom表示:

    Новини, останні події https://prp.org.ua в Україні та світі, новини політики, бізнесу та економіки, законодавства

  6. I was suggested this website by my cousin. I’m not sure whether this post
    is written by him as nobody else know such detailed about
    my trouble. You are incredible! Thanks!

    Also visit my blog post – denticore reviews

  7. музыкальное оборудование для актового зала http://www.oborudovanija-dlja-aktovyh-zalov.ru .

  8. phen q表示:

    What’s up, always i used to check blog posts here in the early hours in the dawn, as i like to learn more and more.

    my blog phen q

  9. Right here is the perfect blog for anybody who hopes to understand this topic.
    You realize so much its almost hard to argue with you (not that I personally would want to…HaHa).
    You definitely put a new spin on a subject that has
    been discussed for ages. Wonderful stuff, just great!

  10. стоимость видеостены стоимость видеостены .

  11. What’s Going down i’m new to this, I stumbled upon this I’ve discovered It
    positively helpful and it has aided me out loads. I am hoping to contribute
    & assist other customers like its helped me. Great job.

  12. световое оборудование для актового зала световое оборудование для актового зала .

  13. renovar sofa表示:

    Hi, Neat post. There’s a problem along with your site in internet explorer, might check
    this? IE still is the marketplace leader and a big element of folks will pass over your great writing because
    of this problem.

  14. Найдите рабочее зеркало 1вин для беспрепятственного доступа.

  15. phimxét表示:

    My developer is trying to persuade me to move to .net from PHP.
    I have always disliked the idea because of the costs. But he’s tryiong none the less.
    I’ve been using Movable-type on several websites for about a year and am concerned about switching
    to another platform. I have heard excellent
    things about blogengine.net. Is there a way I can transfer all my wordpress content into it?
    Any help would be really appreciated!

  16. Offer More Options To Customers With Credit Card Processing 대학생 생활비 대출 (guestbook.southbeachresidentialblog.com)

  17. Hey I am so thrilled I found your webpage, I really found you by mistake, while I was
    researching on Bing for something else, Nonetheless I am here now and would just like to say many thanks for a
    remarkable post and a all round enjoyable blog (I also love the theme/design),
    I don’t have time to browse it all at the minute but I have bookmarked it and also added your RSS
    feeds, so when I have time I will be back to read a lot more, Please
    do keep up the excellent job.

    Feel free to surf to my page – http://superpremium2.premium4best.eu/

  18. 1вин зеркало рабочее всегда доступно для вас.

  19. Hello, I read your blogs daily. Your story-telling style is awesome, keep it
    up!

  20. I’m not that much of a internet reader to be honest but your
    sites really nice, keep it up! I’ll go ahead and
    bookmark your site to come back in the future. All the best

  21. 1вин зеркало обеспечивает стабильный доступ к любимым играм.

  22. How Obtain A Loan With No Credit Check: It’s Not Hard!

    학자금 대출

  23. Excellent article. Keep posting such kind of information on your site.
    Im really impressed by it.
    Hey there, You have performed a great job. I’ll certainly digg it and in my opinion recommend
    to my friends. I am confident they’ll be benefited from this web
    site.

  24. A Glaring Gambling Error – Why Do Even Math Experts And
    Gambling Gurus Commit It? 에볼루션 바카라 사이트

  25. It’s going to be end of mine day, but before finish I am reading this wonderful article to increase my knowledge.

  26. The Conveniences Having A Bank Account Online 공무원 대출 (clicavisos.com.ar)

  27. Зеркало 1win поможет вам продолжить игру без перебоев.

  28. porn表示:

    Ever looked for a quick and easy way to start generating money but felt like there was practically nothing you may do? That’s just not legitimate anymore. The web has provided us with extra methods to make money than we’ve ever experienced up to now.

    In excess of decades, the music has become an anthem to mock capitalist obsession and profits disparities, a standard societal theme today. It carries on for use in different media, such as movies, television collection and commercials.

    Time and energy to initially payment: Once you promote an item, count on a wait around period of around five times to receive resources within your checking account on most platforms.

    Monetize your Twitch channel by promoting goods utilizing the Shopify Starter Approach—This really is An easily affordable alternate to a full ecommerce Internet site plan.

    It’s possible you’ll notice that other discounts goods meet your monetary demands a lot better than a money sector account. Below are many of the alternatives you might want to look at.

    Request about withdrawal selections and the surplus transaction fee of every institution prior to deciding to open up an account.

    Web builders are entrance-conclusion builders use programming languages which include HTML, CSS, and Javascript to develop web pages for Internet sites. In addition they must enhance Web page effectiveness.

    Watch all investmentsStocksFundsBondsReal estate and alternative investmentsCryptocurrencyEmployee equityBrokerage accounts529 university personal savings plansInvestment account reviewsCompare online brokerages

    Thinking about customers are now observinghttp://www.owens-removals.co.uk/ several of the best money marketplace fees they’ve witnessed in many years, this development is likely to carry on so long as banking companies are ready to contend for new deposits. On the other hand, prices are more likely to commence trending downward in some unspecified time in the future following calendar year.

    If you like animals, it’s possible you’ll offer you pet sitting down services in your house. Pet owners can take advantage of your services any time They are really out of city or just have to have a split. You should choose whether or not you should care for puppies, cats or all kinds of Animals.

    Work amount: Medium to substantial, based on products and talent to develop a shopper base. Very low energy to take care of.

    Our professionals rated Sallie Mae Lender’s money industry account highly because savers can pair this aggressive MMA With all the bank’s SmartyPig price savings account. The SmartyPig Account includes equipment to build and monitor progress towards particular money ambitions—like an internet piggy financial institution.

    Money industry accounts typically use tiered curiosity fee structures to award much better rates to customers with bigger balances. Determine which stability tier you’d most likely tumble into ahead of opening an account.

    Video is now an increasingly common variety of marketing and advertising and marketing, and many firms are starting their particular YouTube channels. Anybody who appreciates how you can edit movies professionally can make money by providing this service. Well-liked application to employ contain
    http://www.owens-removals.co.uk/

    PORN
    MONEY

發佈留言

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