psd.js 解析PSD文件



前言

记录一下psd.js解析PSD文件


一、vue导入psd.js

npm install --save psd.js

详情参考github,psd.js: https://github.com/meltingice/psd.js

二、解析psd文件

使用el-upload上传psd文件

<template>
  <div>
    <el-upload
      :auto-upload="false"
      :on-change="parsePSD"
      class="upload-demo"
      drag
      action=""
    >
      <i class="el-icon-upload" />
      <div class="el-upload__text">点击添加或拖放PSD文件</div>
    </el-upload>
  </div>
</template>

<script>
// 引入psd.js 
import PSD from 'psd.js'
export default {
    
    
  methods: {
    
    
    parsePSD(file) {
    
    
      // psd文件
      var url = URL.createObjectURL(file.raw)
      // 解析psd文件
      PSD.fromURL(url).then(psd => {
    
    
        console.log(psd)
        // psd背景图片
        const l_background = psd.image.toBase64()

        // 获取图层数据
        const childrens = psd.tree().children()
        childrens.forEach(item => {
    
    
          if (item._children.length > 0) {
    
    
            // 子节点图层
            const _child = item._children
            _child.forEach(i => {
    
    
              const typeTool = i.get('typeTool')
              if (typeof typeTool !== 'undefined') {
    
    
                // 获取字间距
                if (typeof (typeTool.styles().Tracking) !== 'undefined') {
    
    
                	console.log(typeTool.styles().Tracking[0])
                }
              }
              // 获取子图层图片
              const child_image = i.layer.image.toBase64()
            })
          }
        })

        // 导出图层数据
        var exportData = psd.tree().export()
        const _export_childrens = exportData.children
        for (var i = 0; i < _export_childrens.length; i++) {
    
    
          // 顶级图层/文件夹
          const name = _export_childrens[i].name
          var i_child = _export_childrens[i].children

          if (typeof (i_child) !== 'undefined') {
    
    
            for (var j = 0; j < i_child.length; j++) {
    
    
              // 子图层数据
              console.log(i_child[j])
            }
          }
        }
      })
    }
	}
}
</script>

三 、psd方法

1.psd背景图转为base64格式

PSD.fromURL(url).then(psd => {
    
    
	console.log(psd.image.toBase64())
}

2.获取节点的所有直接子节点

PSD.fromURL(url).then(psd => {
    
    
	console.log(psd.tree().children())
}

_children中为所有子节点图层
在这里插入图片描述

3.文字图层获取字间距

PSD.fromURL(url).then(psd => {
    
    
	const parent = psd.tree().children()
	const typeTool = parent._chilren[0].get('typeTool')
	console.log(typeTool.styles().Tracking[0])
}

4.子图层背景图

PSD.fromURL(url).then(psd => {
    
    
	const parent = psd.tree().children()
	const children = parent._chilren[0]
	console.log(children.layer.image.toBase64())
}

5.导出数据

PSD.fromURL(url).then(psd => {
    
    
	console.log(psd.tree().export());
}

在这里插入图片描述
在这里插入图片描述
字体信息
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Peanutfight/article/details/125815776