image2code.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. const fs = require('fs')
  2. const path = require('path')
  3. // 指法文件夹位置
  4. // const filesDir = path.join(__dirname, './fingering')
  5. // const filesDir = path.join(__dirname, './pages/detail')
  6. const filesDir = path.join(__dirname, './images')
  7. console.log("🚀 ~ filesDir:", filesDir, path.join(filesDir, 'index.json'))
  8. // 需要处理的文件后缀
  9. const suffixs = ['png', 'svg']
  10. const files = fs.readdirSync(path.resolve(filesDir))
  11. // console.log("🚀 ~ files:", files)
  12. ;(async function() {
  13. let i = 0
  14. const exportJson = {}
  15. for (const file of files) {
  16. const suffix = file.slice(file.lastIndexOf('.') + 1)
  17. // console.log("🚀 ~ suffix:", suffix)
  18. if (!suffixs.includes(suffix)) continue;
  19. const dirFullPath = path.join(filesDir, file)
  20. // console.log("🚀 ~ dirFullPath:", dirFullPath)
  21. fs.stat(dirFullPath, (err, stat) => {
  22. if (!err && !stat.isDirectory()) {
  23. const fileNames = file.split('.')
  24. const fileBuffer = fs.readFileSync(dirFullPath)
  25. console.log("🚀 ~ fileBuffer:", fileNames[0])
  26. const fileType = suffix === 'svg' ? 'svg+xml' : suffix
  27. const str = `data:image/${fileType};base64,` + Buffer.from(fileBuffer, 'binary').toString('base64')
  28. exportJson[fileNames[0]] = str
  29. fs.writeFileSync(path.join(filesDir, 'index.json'), JSON.stringify(exportJson, null, 2))
  30. }
  31. })
  32. // if (i === 0) break;
  33. }
  34. })()