
Un liviano liviano Photoshop .psd/.psb Parser en TypeScript con dependencia cero para navegadores web y NodeJs
@webtoon/psd es un analizador rápido y ligero para archivos Adobe Photoshop PSD/PSB. Utiliza funciones estándar (ES2015+) y se puede usar tanto en navegadores web como en node.js. Toma dependencias cero, lo que lo hace más pequeño (~ 100 kib de minificado) que otros analizadores de PSD (Ag-PSD: 200 KIB, PSD.JS: 443 KIB). Utiliza WebAssembly para acelerar los datos de la imagen de decodificación.
| Cromo | Firefox | Safari | Borde | Nodo |
|---|---|---|---|---|
| 57 | 52 | 11 | 79 | 12 |
*Internet Explorer no es compatible
$ npm install @webtoon/psdPuede ejecutar puntos de referencia para @Webtoon/PSD en su navegador.
.psb ) @webtoon/psd se proporciona como un módulo ECMAScript puro.
Consulte la demostración en vivo (código fuente) para el navegador web.
@webtoon/psd debe estar incluido con un Bundler como Webpack o Rollup.
@webtoon/psd lee un archivo PSD como ArrayBuffer . Puede usar FileReader o File para cargar un archivo PSD:
import Psd from "@webtoon/psd" ;
const inputEl : HTMLInputElement = document . querySelector ( "input[type='file']" ) ;
inputEl . addEventListener ( "change" , async ( ) => {
const file = inputEl . files [ 0 ] ;
const result = await file . arrayBuffer ( ) ;
const psdFile = Psd . parse ( result ) ;
const canvasElement = document . createElement ( "canvas" ) ;
const context = canvasElement . getContext ( "2d" ) ;
const compositeBuffer = await psdFile . composite ( ) ;
const imageData = new ImageData (
compositeBuffer ,
psdFile . width ,
psdFile . height
) ;
canvasElement . width = psdFile . width ;
canvasElement . height = psdFile . height ;
context . putImageData ( imageData , 0 , 0 ) ;
document . body . append ( canvasElement ) ;
} ) ;Para el rendimiento, recomendamos analizar archivos PSD en un trabajador web en lugar del hilo principal.
Consulte el código fuente del ejemplo de nodo.js para el navegador web.
@webtoon/psd no admite el Buffer Node.js. Debe suministrar explícitamente el ArrayBuffer subyacente.
import * as fs from "fs" ;
import Psd from "@webtoon/psd" ;
const psdData = fs . readFileSync ( "./my-file.psd" ) ;
// Pass the ArrayBuffer instance inside the Buffer
const psdFile = Psd . parse ( psdData . buffer ) ; Dado que @webtoon/psd se proporciona como un módulo ES, debe usar Dynamic import() o un Bundler para ejecutarlo en el código CommonJS:
const Psd = await import ( "@webtoon/psd" ) ; Esta biblioteca proporciona la clase Psd como la exportación predeterminada.
Psd.parse(ArrayBuffer) toma un ArrayBuffer que contiene un archivo PSD o PSB y devuelve un nuevo objeto Psd .
const psdFile = Psd . parse ( myBuffer ) ; Un objeto Psd contiene un árbol de objetos de Layer y Group (es decir, grupo de capa).
Psd proporciona una propiedad children , que es una variedad de Layer de nivel superior y Group S.Group proporciona una propiedad children , que es una variedad de Layers y Group que pertenecen inmediatamente bajo el grupo de capa actual.Psd , Group y Layer proporcionan un campo type , que se puede usar para discriminar cada tipo: import Psd , { Node } from "@webtoon/psd" ;
// Recursively traverse layers and layer groups
function traverseNode ( node : Node ) {
if ( node . type === "Layer" ) {
// Do something with Layer
} else if ( node . type === "Group" ) {
// Do something with Group
} else if ( node . type === "Psd" ) {
// Do something with Psd
} else {
throw new Error ( "Invalid node type" ) ;
}
node . children ?. forEach ( ( child ) => traverseNode ( child ) ) ;
}
traverseNode ( psdFile ) ; El objeto Psd también proporciona la propiedad layers , que es una matriz de todas Layer en la imagen (incluida la anidada).
for ( const layer of psdFile . layers ) {
doSomething ( layer ) ;
} Use Psd.prototype.composite() y Layer.prototype.composite() para decodificar la información de píxeles para toda la imagen o una capa individual.
Tenga en cuenta que para que funcione Psd.prototype.composite() , los archivos PSD/PSB deben guardar en el modo "Maximizar la compatibilidad". De lo contrario, no devolverá datos. Puede habilitarlo en Preferences > File Handling > File Compatibility > Maximize PSD and PSB File Compatibility
// Decode the pixel data of the entire image
pixelData = await psd . composite ( ) ;
// Extract the pixel data of a layer, with all layer and layer group effects applied
// (currently, only the opacity is supported)
layerPixelData = await layer . composite ( ) ;
// Extract the pixel data of a layer, with only the layer's own effects applied
layerPixelData = await layer . composite ( true , false ) ;
// Extract the pixel data of a layer, without any effects
layerPixelData = await layer . composite ( false ) ; @webtoon/psd se lanza bajo la licencia MIT.
Copyright 2021-present NAVER WEBTOON
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.