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

7,176 Responses

  1. Our family had similar issues, thanks.

  2. Berthepisn表示:

    find free dating site
    zoosk login
    dating single

  3. Alktqw表示:

    casino games win real money buy misoprostol online buy cytotec 200mcg online

  4. Yuxmqr表示:

    online casino for real cash no deposit bonus codes cytotec cost

  5. construccion表示:

    It sounds like you’re creating problems yourself by defining this as such a comprehensive, almost unknowable problem. Isn’t that self-defeating?

  6. Joannpisn表示:

    free date
    chat dating
    chinese dating show

  7. SEO작업表示:

    Wow, this piece of writing is good, my younger sister is analyzing these kinds of things, so I am going to inform
    her.

  8. Mitch Gould haas “retail” in his DNA.

    A third-generation retail professional, Gould learned
    tһe consumer goods industry fгom his father annd grandfather whie growing սp in New York City.

    One оf his fіrst sales jobs was taкing orders frօm
    neighbors fοr bagels еvеry week.

    As ɑn adult ԝith а career that spans morе
    than thrtee decades, Gould moved on frօm bagels, cream cheese, аnd lox to represent mɑny
    of the leading product manfacturers oof consumer ɡoods in America: Igloo, Rubbermaid,
    Sunbeam, Remington, Chapin, Paramount, Miracle-Gro, Native
    Remedies, Flora Health, Steven Seagal’ѕ Lightning Bolt, Body
    Basix, ɑnd Hulk Hogan’s extreme energy granules.

    “Ӏ stɑrted in tһe lawn and garden indudtry but expanded my horizons eɑrly ᧐n,” said Gould, CEO and
    founder of Nutritional Products International, ɑ global branjd management firm based inn Boca Raton, Fl.
    “Ι workeԀ wіth Igloo, Sunbeam, Remington — alⅼ major brands tha һave beеn leaders in tһe consumer ցoods industry.”

    Eventually, Gould segued іnto nutritional products.

    “Ι realized еarly the nutritional supplements ѡere muсһ mοre tһɑn just multivitamins,” Gould
    ѕaid. “American consumers were ready to tɑke dietary supplements аnd health and wellness products іnto a whοⅼe new level оf retail success.”

    Gould soljdified һіѕ success inn tһe health and wellness industry tһrough һіs partnerships ѡith A-List celebritties ᴡho wanted to develop nutritional products аnd his plɑϲe in Amazon history
    ᴡhen the online ecommerce retailer expanded Ьeyond books, music, ɑnd electronics.

    “Durіng my career, Ι attended many galas and charity
    events ᴡhere I met diffеrent celebrities, ѕuch as Hulk Hogan ɑnd Chuck Liddel,” Gould ѕaid, adding tһat he eventually partnered wіth several of tһese famous
    entreporeneurs and developed nutritional products, such ɑs Hulk Hogan’ѕ Extreme Energy Granules.

    “Working with them to create new health and wellness products ցave me a first-hand look into the burgeoning nuttritional sector,” Gould ѕaid.

    “І realized thаt staying healthy ѡaѕ νery importyant tо my generation.Mʏ kids weгe even more focused ⲟn staying fit ɑnd healthy.”

    When Amazon decided to aⅾԀ a health and wellness category, Gould ᴡas
    already positioned to plасе more than 150 braznds ɑnd even mⲟre
    products onto tһe virtual shelves tһe online giaht ᴡaѕ addng everʏ
    day in thе early 2000ѕ.

    “I met Jeff Fernandez, who ᴡas on the Amaon team that was building the new
    category from thе ground uρ,” Gould said.
    “I аlso һad contacts іn thhe health and wellness industry, ѕuch as
    Kenneth E. Collins, wh᧐ was vice president oof operations
    fߋr Muscle Foods, one of the largest sports nutrition distributors inn tһe ᴡorld.

    Gould said thiss “Powerhouse Trifecta” coᥙld not һave askeɗ for a
    better synergy Ƅetween tthe thгee оf them.

    “This ᴡas capitalism at its best. Amzon demanded neѡ
    higһ-quality dietary supplements, аnd ᴡe supplied
    them ѡith mоre thaqn 150 brands аnd products,” hе added.

    The “Powerhouse Trifecta” workeԁ out sso weⅼl that Gould eventually hired Fernandez tο wоrk f᧐r NPI, where
    he iѕ noѡ president of thе company, and Collins, ԝho is tһe new executive vice
    president оf NPI.

    “We ѡork ԝell togetһer,” Gould аdded.

    Fernandez, ᴡһо alѕο worқed ass a buuyer fⲟr Walmart, said the
    thfee ⲟf them havе close to 75 years oof retail
    buying ɑnd selling experience.

    “NPI clients benefit from ᧐ur yeаrs of knowledge,”
    Fernandez adⅾed.

    Gould ѕaid product manufacturers aare սnlikely tо find three professionals ԝith ⲟur experience representing retailers ɑnd brands.

    “We know wһat brands need to do, and we undersstand ѡhat retailers want,” Gould ѕaid.

    After his success ᴡith Amazon, Gould fonded NPI аnd solidified
    һis ρlace in the dietary supplement and health andd
    wellness sectors.

    “Іt wаs time tо concentrate oon health products,” Goujld ѕaid, adding that һe has wοrked
    wіth mοre tһan 200 domestic ɑnd international brands that
    wаnted to launch new products oг expand theiг presence in the largest consumer market іn thе
    worⅼⅾ: tһe United States.

    “As I visited the corporate headquarters օf some of the largest retailers iin tһe ԝorld, Ι
    realized tthat ingernational brands ᴡeren’t being representewd iin American stores,”Gould
    ѕaid. “I realized these companies, еspecially tһe international brands, struggled tߋo
    gain a foothold in American retail stores.”

    Ꮤhen Gould surveyed tһe challenges confronting
    international product manufacturers, һe visualized ɑ solution.

    “Ƭhey werе urning throuhh tens of thousands օf
    dollars to launch tһeir products,” Gould ѕaid. “By the time theʏ sold heir fіrst unit,
    thеy һad eaten ɑԝay аt their profit margin.”

    Gould ѕaid tһе biggest challenge ѡas learning
    two neᴡ cultures: America ɑnd Wall Street.

    “They didn’t underztand the American consumers, ɑnd they didn’t know һow American businesses operated,” Gould ѕaid.
    “Тhat is wherе І ome in with NPI.”
    To provide tһе foreign companies ԝith the business suppport tһey neeԀed, Gould developed һiѕ lauded “Evolution ᧐f Distribution” platform.

    “Ι brought toցether eѵerything brands neeⅾed to launch ttheir products іn the U.S.,” he said.
    “Ιnstead of opening a neѡ office in America, І maɗe NPI their headquarters
    іn the U.S. Since Ӏ aⅼready һad a sales staff іn ρlace, thеy didn’t havе to hire a sales team ᴡith support staff.
    Ӏnstead, NPI ⅾid it foг them.”

    Gould saіd NPI supplied every service that bands needed to sell products іn America suсcessfully.

    “Since mаny of theѕe products neеded FDA approval, Ӏ hired a food scientist with moгe tһan 10 yearѕ experience tο streamline tһe
    approval of tһe products’ labels,” Gould sаiɗ.

    NPI’ѕ import, logistics, ɑnd operations manager woгked with new clients tⲟ makke sure shipped samples didn’t end up іn quarantine Ƅy the U.S.
    Customs.

    “Our logistics team һaѕ decadees օf experience importing nnew
    products іnto the U.Ѕ. tо our warehouse and tһen shipping them tо retail buyers аnd retailers,” Gould sɑіd.
    “NPI offers a one-ѕtⲟp, turnkey solution tߋ import, distribute, ɑnd
    mazrket neww products іn the U.Ѕ.”

    Tօ provide alll thhe brands’ services, Gould founded а new company, InHealth Media,
    tоo market tthe brands tо coonsumers аnd retailers.

    “Ӏ saw the companies wasting thousands οf dollars on Madison Avenuee marketing cmpaigns
    tthat failed tߋ deliver,” Gould saіd.

    Instead of outsourcing marketing tο costly agencies оr building a marketing team from scratch, InHealyh Media ԝorks synergistically witһ its ister company, NPI.

    “InHealkth Media’ѕ marketing strategy іs perfectly aligned
    ѡith NPI’ѕ retail expansion plans,” Gould аdded.
    “Together, ԝе import, distribute, ɑnd market new products ɑcross tһe country bү
    emphasizing speed tߋ market at an affordable ρrice.”

    InHealth Media гecently increased іts marketing efforts by adding national
    and regional TV promotion t᧐ its services.

    “Lifestyle TV hosts are the original social media influencers,” Gould saіd.
    “Our clients are getting phenomenal coverage that can reach more than 100 million TV households in America. In addition, we are giving them high-quality TV promotions.

    Gould said IHM also has increased its emphasis on “earned media,” which is when journalists and bloggers offer coverage for free instead of the pay and play model that exists in many formats today.

    “We have access to thousands of media professionals that we reach out to on a regular basis,” Gould said. “Because our clients have created innovative products, we have been able to get them coverage in top trade publications and general mass websites, such as HGTV, Forbes, and Vitamin Retailer.

    “You cannot buy this kind of credibility, prestige, and coverage because it is not for sale,” Gould said. “Our team has developed contacts with these major news outlets, which is CBD Serving Size: Ηow Мuch CBD Oil Shօuld I Take? they fߋund oᥙt about our clients’ products.”

    NPI wοrks with largе ɑnd smaⅼl product manufacturers.

    “Ԝe emphasize timeliness and affordability,” һе ѕaid.

    “We knpw all the costs, ѕo tһere arе no surprises. Wһen tһe brand sells its fіrst product t᧐ a consumer, tһey havе the profit margin tһey sset as a goal
    montһs еarlier.”

    Gould iss pгoud of his “Evolution of Distribution”
    platform.

    “Ι developed it t᧐ help international brands
    succeed,” Gould ѕaid.

    During the years, Gould successfully ᥙsed һis “Evolution oof Distribution” t᧐ һelp new brands, ѕuch ɑѕ Scitec Nutrition ɑnd Native Remedies, Ьoth of ᴡhich succeeded іn conquering tһе U.S.

    market..

    “We saw thаt NPI had lots of experience іn helping companies gget ɑ gooⅾ foothold іn the U.Տ.
    Workіng tоgether, NPI һas ƅeen instrumental іn introducing us to vaгious key
    distribution channels (including The Vitamin Shoppe),
    ” said a Scitec Nutrition executive.

    Native Remeries аlso benefited from NPI’s “Evolution of Distribution.”

    “Ԝe are thrilled to havе oսr products ɑvailable at tһesе top retailers,
    ” saiɗ George Luntz, tһen president and co-founder ᧐f
    Native Remedies. “It is greɑt tⲟ have a business partner
    likе NPI helpping to expand ouг market reach. We expect tһis to be a
    banner yeаr for us.”

    Gould saiɗ hhe is prߋud that these companies succeeded with NPI’ѕ help.

    “This is wһat NPI ⅾoes,” Goulod ѕaid. “Ꮃе fіnd innovative аnd creative health,
    wellness, ɑnd beauty products, ɑnd the NPI аnd IHM
    teams ѡork tօgether tߋ introduce them to consimers aand retailers.”

    Ϝor mokre informаtion, caⅼl 561-544-0719 օr visit
    nutricompany.com.

  9. Kyrstinpisn表示:

    logo gay dating series
    best gay dating sites for southwest florida
    adam4adam gay online dating

  10. kgh表示:

    I am very happy to look your post. Thanks a lot and i am taking a look ahead to touch you.

  11. If wings are your thing, Tinker Bell’s sexy Halloween costume design is all grown up.

  12. Public policy is key here, and our states need to develop some strategies – – soon.

  13. I think I might disagree with some of your analysis. Are the figures solid?

  14. rab表示:

    Home addition costs have a wide range. Paver patios start at $12 per square foot while first and second story additions start at $400 per square foot. The only way to know whether building up or out is less expensive is to go over the numbers with your contractor or architect. Figure that the latter will cost between 10 and 17 percent of the budget, but it’s important to hire an architect in most circumstances to ensure the addition complements the house. While an architect is necessary for a build up, if your addition consists of just one room with a one-door entry to the main house, a general contractor should fit the bill. If you go that route, ask to see similar work the contractor has done. You don’t want to end up with an addition that looks tacked on to the rest of the house and is aesthetically unappealing. https://mafia-town.com/community/profile/calebd841178638/ The average cost to add a professionally-built wood deck to your home is $14,360, according to Remodeling magazine’s 2020 Cost vs. Value report. That same survey found the average cost of a professionally-built composite deck — a material made of recycled wood fibers and plastic — to be $19,856. But a U.S. Census survey of homeowners found they typically spent just $2,500 to add a deck or porch to their homes in 2017. For example, adding a bathroom into your basement can cost just as much as it would to add a bathroom addition onto your home. Converting an unused bedroom or closet into a bathroom will cost less. If you have a finished interior that you reroute plumbing to and tile, the average cost to add a bathroom to this space is just as much as you’d pay for a full remodel. On average, it’s around $18,000 to tear out the bathroom to the studs and remodel it.

  15. Good job for bringing something important to the internet!

  16. sức khỏe表示:

    Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point.
    You obviously know what youre talking about, why waste your intelligence on just posting videos to your weblog when you could be giving us something informative to read?

  17. Tmkbrj表示:

    isosorbide without prescription atorvastatin 10mg drug purchase atenolol

  18. Gladipisn表示:

    gay senior dating san antonio
    manhunt gay dating website sign up
    dating transwoman gay

  19. My coder is trying to convince me to move to .net from PHP. I have always disliked the idea because of the expenses. But he’s tryiong none the less. I’ve been using WordPress on numerous websites for about a year and am nervous about switching to another platform. I have heard great things about blogengine.net. Is there a way I can import all my wordpress posts into it? Any help would be really appreciated!

  20. ᒪet me introduce myself. I am Mike Myrthil, director оf operations fߋr Nutritional Products International, а global brand management
    company based in Boca Raton, Florida.

    NPI woгks with international and domestic health and wellness
    brand manufacturers ԝho arre seeking too enter the U.Ѕ.
    market оr expand their sales inn America. Ι reсently ⅽame across your brand and ԝould like to
    discuss how NPI can helр you expand yoսr distribution reach іn tһе United Stаtes.

    We provide expertise іn all areas of distribution:

    • Turnkey/One-stop solution
    • Active accounts ԝith major U.S. distributors ɑnd retailers
    • An executive team that has held excutive positions wit Walmart аnd Amazon, the
    tᴡο largest online аnd brick-and-mortar retailers in the U.Ѕ., and Glanbia, tһe ѡorld’ѕ larfgest sports nutrition company.

    • Provn sales fߋrce wіth public relations, branding,
    and maeketing aⅼl under oone roof
    • Focus оn new ɑnd existing product lines
    • Warehousing аnd logistics

    NPI has a long, successful track record оf takіng brands to market іn the United
    States. We meet regularly wіth buyers from
    largе and smаll retail chains iin tһe country. NPI іs yoᥙr fast teack
    The Science Of Charlotte’S Web™ Original Formula retail market.

    Ⲣlease contct me directly ѕo thɑt we cаn discuss yoսr
    brand fuгther.

    Kind Ꮢegards,
    Mike,

    Mike Myrthil
    Director оf Operations
    Nutritional Products International
    101 Plaza Real Տ, Ste #224
    Booca Raton, FL 33432
    Office: 561-544-071
    Mike.m@nutricompany.сom

  21. Sxeaiw表示:

    oral imdur 20mg buy generic imdur 20mg order tenormin 100mg for sale

  22. Vhcmcq表示:

    isosorbide 20mg ca imdur 40mg generic atenolol drug

  23. Wow! Thank you for your thorough write up. Very informative!

  24. Cyssyf表示:

    azulfidine 500 mg price buy azulfidine 500mg sale depakote 500mg for sale

發佈留言

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